您的位置:首页 > 编程语言 > Python开发

python 模式集锦

2016-03-16 11:42 453 查看
摘要: 现在,仍是很怀念java啊~
那就看看python里都有哪些好的模式吧!

发布订阅模式:

发布订阅模式,是一种编程方式,消息的发送者不会将消息发送给特定的接收者,而是将不同类型的消息直接发送,并不关注订阅者是谁,订阅者只负责订阅消息,且只接收订阅过的消息不关注消息发布者
发布订阅模式——功效:解耦

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# time @2016/3/16 11:30 create by JasonYang

from collections import defaultdict

container = defaultdict(list)

def sub(topic, callback):
if callback in container[topic]:
return
container[topic].append(callback)

def pub(topic, *args, **kwargs):
for func in container[topic]:
func(*args, **kwargs)

def greeting(name):
print "hello %s" % name

sub('greet', greeting)
pub('greet', 'dashu')


代理模式:

功效:为其他对象提供一个代理以控制对这个对象的访问

# -*- coding:utf-8 -*-
# 2016/8/18
# mail:ybs.kakashi@gmail.com

class Implementation(object):
def f(self):
print str(self.__class__) + "f()"

def g(self):
print str(self.__class__) + "g()"

def h(self):
print str(self.__class__) + "h()"

class ImpProxy(object):
def __init__(self):
self.__impl = Implementation()

def __getattr__(self, item):
return getattr(self.__impl, item)

p = ImpProxy()
p.f()
p.g()
p.h()


状态模式

让一个对象在其内部状态改变的时候,其行为也随之改变。状态模式需要对每一个系统可能获取的状态创立一个状态类的子类。当系统的状态变化时,系统便改变所选的子类。

# -*- coding:utf-8 -*-
# 2016/8/18
# mail:ybs.kakashi@gmail.com

class State(object):
def __init__(self, impl):
self.__implementation = impl

def change_impl(self, new_impl):
self.__implementation = new_impl

def __getattr__(self, item):
return getattr(self.__implementation, item)

class Impl1(object):
def f(self):
print str(self.__class__) + "f()"

def g(self):
print str(self.__class__) + "g()"

def h(self):
print str(self.__class__) + "h()"

class Impl2(object):
def f(self):
print str(self.__class__) + "f()"

def g(self):
print str(self.__class__) + "g()"

def h(self):
print str(self.__class__) + "h()"

def run(s):
s.f()
s.g()
s.h()
s.g()

state = State(Impl1())
run(state)
print "implementation changed"
state.change_impl(Impl2())
run(state)


混入

http://my.oschina.net/u/2504425/blog/739396
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: