用装饰器和类实现的Python设计模式。

meta-patterns的Python项目详细描述


元模式

用装饰器和类实现的Python设计模式。在

入门

目前只实现了一种设计模式:Listener。在

侦听器模式

Listener模式(也称为ObserverPublish-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!在

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
由于java的原因,maven无法运行代码。lang.NoClassDefFoundError:com/fasterxml/jackson/annotation/JsonMerge   Android项目中的java Creative SDK图像编辑器UI   java如何在Android Studio中使用DataOutputStream上传文件并将其他参数传递到web服务器   java倒计时服务打开时崩溃   java将RubyonRails项目转换为JRubyonRails项目   java我的图库意图是不显示图像?为什么?   java如何在春季启动时跳过mongodb/   java@Autowired在Spring中是如何实现的   甲骨文Akka java。util。同时发生的timeoutexception线程池频繁超时   java maven依赖项对spring启动应用程序有何影响?   java Firestore执行复合查询,未截获事件“已修改”   java ItemStreamException:未能初始化读取器,原因是:IllegalStateException:流已初始化。重新开放前关闭   java将空标记解组到集合的新实例中   使用AspectJ的java新手:无法调用aspect   java查找棋类游戏的所有组合   你为什么要这样做and==与Java中的equals方法不一样吗?   如何对使用JavaUUID的代码进行单元测试?