行为模式观察者模式
意图
可在对象事件发生时通知多个 “观察” 该对象的其他对象。
核心: 被观察者与观察者建立一种自动触发的关系.
模式分析
在热水器模型中
被监听者:热水器的温度(会发生变化).
监听者: 不同的水温,不同的监听者会及时的作出反应.
被观察者:
- 添加监听者
- 删除监听者
- 通知监听者.触发观察者的提供接口.
使用场景.
- django 信号机制
2.推模型和拉模型
*推模型: 被观察者向观察者推送.
*拉模型:
#!/usr/bin/env python
from abc import ABCMeta, abstractmethod
class Observer(metaclass=ABCMeta):
"""
观察者基类:
"""
@abstractmethod
def update(self, water_heater):
"""
订阅更新事件.
:param water_heater:
:return:
"""
print("xxx WaterHeater:{}".format(water_heater))
class Observable(metaclass=ABCMeta):
"""
被观察者基类:
"""
def __init__(self):
self.__observers = []
def __str__(self):
return f"observers:{self.__observers}"
def register(self, observer):
if not isinstance(observer, Observer):
raise TypeError("observer must be instance of Observer")
self.__observers.append(observer)
def unregister(self, observer):
self.__observers.remove(observer)
def notice(self):
"""
通知订阅者事件发生
:return:
"""
for o in self.__observers:
# if hasattr(o, "update"):
o.update(self)
class WaterHeater(Observable):
"""
热水器
"""
def __init__(self):
super().__init__()
self.__temperature = 25
def __str__(self):
print(super().__str__())
return f"cur temperature:{self.__temperature}"
@property
def temperature(self):
return self.__temperature
@temperature.setter
def temperature(self, val):
self.__temperature = val
print(self)
self.notice()
class Account(Observable):
"""
登陆地记录
"""
def __init__(self):
super().__init__()
self.__city_history = list()
def __str__(self):
print(super().__str__())
return f"cur city_history:{self.__city_history}"
@property
def city(self):
return self.__city_history[-1]
@city.setter
def city(self, val):
if val not in self.__city_history:
self.__city_history.append(val)
print(self)
self.notice()
class WashMode(Observer):
"""
洗澡模式
"""
def update(self, water_heater: WaterHeater):
if 50 < water_heater.temperature < 70:
print("is good time at wash")
else:
print("not good time at wash")
class DrinkMode(Observer):
"""
饮水模式
"""
def update(self, water_heater: WaterHeater):
if water_heater.temperature >= 80:
print("is good time at drink")
else:
print("not good time at drink")
class SmsMode(Observer):
"""
短信通知
"""
def update(self, account: Account):
"""
:param account:
:return:
"""
print("sms notify ", account.city)
pass
class EmailMode(Observer):
"""
邮件通知
"""
def update(self, account: Account):
"""
:param account:
:return:
"""
print("email notify ", account.city)
def test_water_mode():
water_heater = WaterHeater()
wash_observer = WashMode()
drink_observer = DrinkMode()
water_heater.register(wash_observer)
water_heater.register(drink_observer)
water_heater.temperature = 60
water_heater.temperature = 100
def test_other_area_login():
login = Account()
email = EmailMode()
sms = SmsMode()
login.register(email)
login.register(sms)
login.city = "北京"
login.city = "上海"
def main():
# test_water_mode()
test_other_area_login()
pass
if __name__ == "__main__":
main()
以上是 行为模式观察者模式 的全部内容, 来源链接: utcz.com/z/516433.html