用装饰器和类实现的Python设计模式。
meta-patterns的Python项目详细描述
元模式
用装饰器和类实现的Python设计模式。在
入门
目前只实现了一种设计模式:Listener
。在
侦听器模式
Listener
模式(也称为Observer
或Publish-Subscribe
模式)是一种行为设计模式,它允许您定义订阅机制,以通知多个对象它们正在观察的对象(source)发生的任何事件。在
其用途如下:
frommetapatterns.listenerimportListenable,listenableclassSubject(Listenable):@listenabledefmyfunc(self,arg1):""" @listenable indicates this function can be 'listened in on'. It allows Listeners to hook into it (see MyListener) """print("myfunc called with arg",arg1)return"Hoozah"defmyfunc2(self,arg1):print("myfunc called with arg",arg1)classMyListener(Subject.Listener):""" Identify this class as a listener of `Subject` through inheritance. This makes it so not all listenable methods need to be implemented (they have a default empty implementation in `Subject.Listener`). """defon_myfunc(self,subject,arg1):print("listened in on call to myfunc with arg",arg1)defon_myfunc_finished(self,subject,result,arg1):print("listened in on result of myfunc with arg",arg1,"and result",result)# This cannot be defined because myfunc2 is not a listenable function in Subject#def on_myfunc2(self, arg1):#pass
我们可以按如下方式运行:
^{pr2}$其输出:
# Calling myfunc without listener myfunc called with arg 3# Calling myfunc with listener listened in on call to myfunc with arg 5myfunc called with arg 5listened in on result of myfunc with arg 5 and result Hoozah# Calling myfunc2 with listener myfunc called with arg 7# Calling myfunc again with listener removed myfunc called with arg 5
当Subject.Listener
中没有匹配的对应函数时,Subject.Listener
的子类化具有在Subject
中没有匹配的对应函数时引发TypeError
。这有助于检测在Subject
中更改函数名时出现的难以发现的问题。我们的方法包括这种检查,以防止Listener
模式的松耦合带来的一些问题。在
今后的工作
- 实现更多的设计模式。在
- 建议?联系me!在
- 项目
标签: