• Python 设计模式


    1、观察者模式

    class AbstractSubject:
        def register(self, listener):
            raise NotImplementedError("Must subclass me")
     
        def unregister(self, listener):
            raise NotImplementedError("Must subclass me")
     
        def notify_listeners(self, event):
            raise NotImplementedError("Must subclass me")
     
    class Listener:
        def __init__(self, name, subject):
            self.name = name
            subject.register(self)
     
        def notify(self, event):
            print (self.name, "received event", event)
     
    class Subject(AbstractSubject):
        def __init__(self):
            self.listeners = []
            self.data = None
    
        def getUserAction(self):
            self.data = raw_input('Enter something to do:')
            return self.data
    
        # Implement abstract Class AbstractSubject
    
        def register(self, listener):
            self.listeners.append(listener)
     
        def unregister(self, listener):
            self.listeners.remove(listener)
     
        def notify_listeners(self, event):
            for listener in self.listeners:
                listener.notify(event)
    
     
    if __name__=="__main__":
        # make a subject object to spy on
        subject = Subject()
     
        # register two listeners to monitor it.
        listenerA = Listener("<listener A>", subject)
        listenerB = Listener("<listener B>", subject)
     
        # simulated event
        subject.notify_listeners ("<event 1>")
        # outputs:
        #     <listener A> received event <event 1>
        #     <listener B> received event <event 1>
     
        action = subject.getUserAction()
        subject.notify_listeners(action)
        #Enter something to do:hello
        # outputs:
        #     <listener A> received event hello
        #     <listener B> received event hello
    

    Python Observer Pattern

    因为Python版本是3.3,所以用print()和 input(),替换 print和raw_input。

  • 相关阅读:
    重建二叉树
    数值的整数次方
    二维数组查找
    二进制中1的个数
    LRU算法的精简实现(基于Java)
    华为18.9.5校招笔试题AK
    避免反射和序列化来破坏单例
    Markdown图片存储解决方法-利用阿里云OSS
    基于Java反射的map自动装配JavaBean工具类设计
    多态与类初始化的底层原理
  • 原文地址:https://www.cnblogs.com/xuanyuanchen/p/6344380.html
Copyright © 2020-2023  润新知