# -*- coding:utf-8 -*-
from abc import ABCMeta, abstractmethod
# 抽象观察者
class Observer(metaclass=ABCMeta):
@abstractmethod
def update(self, notice): # notice 是 Notice类的对象
pass
# 抽象主题
class Notice(object):
def __init__(self):
self.observers = []
def attach(self, observer):
self.observers.append(observer)
def detach(self, observer):
self.observers.remove(observer)
def notify(self):
for observer in self.observers:
observer.update(self)
# 具体主题,即发布者
class StaffNotice(Notice):
def __init__(self, company_info):
super(StaffNotice, self).__init__()
self.__company_info = company_info
@property
def company_info(self):
return self.__company_info
@company_info.setter
def company_info(self, info):
self.__company_info = info
self.notify() # 推送
# 具体观察者,即订阅者
class Staff(Observer):
def __init__(self):
self.company_info = None
def update(self, notice):
self.company_info = notice.company_info
# Client
notice = StaffNotice('初始公司信息')
s1 = Staff()
s2 = Staff()
notice.attach(s1)
notice.attach(s2)
print(s1.company_info)
print(s2.company_info)
notice.company_info = '公司今年业绩非常行好,给大家发奖金!!!'
print(s1.company_info)
print(s2.company_info)
notice.detach(s2)
notice.company_info = '明天公司放假!'
print(s1.company_info)
print(s2.company_info)