發佈訂閱模式,是一種編程方式,消息的發送者不會將消息發送給特定的接收者,而是將不一樣類型的消息直接發送,並不關注訂閱者是誰,訂閱者只負責訂閱消息,且只接收訂閱過的消息不關注消息發佈者
發佈訂閱模式——功效:解耦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()
讓一個對象在其內部狀態改變的時候,其行爲也隨之改變。狀態模式須要對每個系統可能獲取的狀態創立一個狀態類的子類。當系統的狀態變化時,系統便改變所選的子類。app
# -*- 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)