79 lines
1.7 KiB
Python
79 lines
1.7 KiB
Python
"""
|
|
实例:
|
|
汤宝宝一时想不开,当了房产中介。
|
|
一旦片区内有房东发布了新房源信息,他就会第一时间通知所有潜在租客。
|
|
"""
|
|
|
|
from abc import ABC, abstractmethod
|
|
|
|
|
|
# 抽象观察者类
|
|
class Observer(ABC):
|
|
@abstractmethod
|
|
def update(self):
|
|
pass
|
|
|
|
|
|
# 抽象目标接口
|
|
class Subject(ABC):
|
|
@abstractmethod
|
|
def attach(self, observer: Observer):
|
|
pass
|
|
|
|
@abstractmethod
|
|
def detach(self, observer: Observer):
|
|
pass
|
|
|
|
@abstractmethod
|
|
def notify(self):
|
|
pass
|
|
|
|
|
|
# 具体目标类
|
|
class HousingAgency(Subject):
|
|
def __init__(self):
|
|
self._observers = []
|
|
|
|
def attach(self, observer: Observer):
|
|
self._observers.append(observer)
|
|
|
|
def detach(self, observer: Observer):
|
|
self._observers.remove(observer)
|
|
|
|
def notify(self):
|
|
print("房产中介通知了所有租客。")
|
|
for observer in self._observers:
|
|
observer.update()
|
|
|
|
|
|
# 具体观察者类
|
|
class Tenant(Observer):
|
|
def __init__(self, name: str):
|
|
self.name = name
|
|
|
|
def update(self):
|
|
print(f"租客{self.name}收到房源更新通知!")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
print("============= 观察者模式 =============")
|
|
|
|
agency = HousingAgency()
|
|
tenant1 = Tenant("小明")
|
|
tenant2 = Tenant("小红")
|
|
|
|
print("小红和小明订阅了房产中介的房源信息。")
|
|
agency.attach(tenant1)
|
|
agency.attach(tenant2)
|
|
|
|
print("房源上新了!")
|
|
agency.notify()
|
|
|
|
print("-----")
|
|
print("小红不想再接收房源信息,退订了。")
|
|
agency.detach(tenant2)
|
|
print("又有新房源了!")
|
|
agency.notify()
|
|
|
|
print("\n=========== 观察者模式结束 ===========")
|