python理解观察者模式(发布——订阅者模式)

*爱你&永不变心* 提交于 2020-02-26 20:04:21
# -*- coding: utf-8 -*-



class Subject:

    def register(self, observer):
        pass

    def unregister(self, observer):
        pass

    def notify(self, msg):
        pass


class Weather(Subject):

    def __init__(self):
        self.observers = []

    def register(self, observer):
        if not observer in self.observers:
            self.observers.append(observer)

    def unregister(self, observer):
        self.observers.remove(observer)

    def notify(self, msg):
        for observer in self.observers:
            observer.do_something(msg)


class Observer:

    def do_something(self, msg):
        pass


class Ruhua(Observer):

    def do_something(self, msg):
        if '雨' in msg:
            print('下雨了,如花可以去桥边等伯虎了')
        elif '雪' in msg:
            print('下雪了,如花可以去堆雪人了')
        elif '太阳' in msg:
            print('出太阳了,如花要去网吧了')


class Cuihua(Observer):

    def do_something(self, msg):
        if '雨' in msg:
            print('下雨了,翠花要做酸菜了')
        elif '雪' in msg:
            print('下雪了,翠花要喂雪人吃酸菜了')
        elif '太阳' in msg:
            print('出太阳了,翠花,上酸菜')


class Cunhua(Observer):

    def do_something(self, msg):
        if '雨' in msg:
            print('下雨了,村花在赏雨')
        elif '雪' in msg:
            print('下雪了,村花在赏雪')
        elif '太阳' in msg:
            print('出太阳了,村花在日光浴')


if __name__ == '__main__':
    ruhua = Ruhua()
    cuihua = Cuihua()
    cunhua = Cunhua()

    weather = Weather()
    weather.register(ruhua)
    weather.register(cuihua)
    weather.register(cunhua)

    weather.notify('下雨了')
    weather.notify('出太阳了')
    weather.notify('下雪了')

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!