用装饰器和类实现的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如何将HashMap<String,Object>从一个活动传递到另一个活动   java如何手动加密socket连接的流量?   java正则表达式生成一个不正确的结果   Java方法引用具有泛型参数的方法   java app setBackground()错误:不兼容的类型:int无法转换为Drawable   java是启动Spring引导而不是SpringApplication的其他方法。跑   无法打开java类路径资源[org/quartz/impl/jdbcjobstore/tables_h2.sql],因为它不存在   spring使用Java,如何确定来自tomcat Web服务器的出站服务调用?   java获取多个同名的XML元素JAXB   java使用Ant从同一代码库构建Swing和Android应用程序   JComponent的java重绘方法不起作用   java目标不可访问,标识符“beanName”解析为null   smtp是否有支持esmtp管道的java api?   java如何在Spring中自动连接业务对象   java在Hibernate中没有其他保存实体的方法吗?   针对两个客户机的SpringJavaWeb应用程序项目开发   使用split的java标记化输入