# -*- 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('下雪了')
来源:CSDN
作者:浪子哥学习笔记
链接:https://blog.csdn.net/qq_36072270/article/details/104520143