from abc import ABCMeta, abstractmethodclassHandler(metaclass=ABCMeta):@abstractmethoddefhandle_leave(self,day):passclassGeneralManager(Handler):defhandle_leave(self,day):if day >10:print("GM: You are fired")else:print("GM: OK, enjoy yourself for %d days"% day)classProjectManager(Handler):def__init__(self):self.next=NonedefsetNext(self,handler):self.next=handlerdefhandle_leave(self, day):if day <=5:print("PM: OK, enjoy yourself for %d days"% day)else:print("PM: I can't decide")self.next.handle_leave(day)classDirectManager(Handler):def__init__(self):self.next=NonedefsetNext(self,handler):self.next=handlerdefhandle_leave(self, day):if day <=1:print("DM: OK, enjoy yourself for %d days"% day)else:print("DM: I can't decide")self.next.handle_leave(day)dm=DirectManager()
pm=ProjectManager()
gm=GeneralManager()dm.setNext(pm)
pm.setNext(gm)dm.handle_leave(8)
from abc import abstractmethod, ABCMetaclassSubscriber(metaclass=ABCMeta):@abstractmethoddefupdate(self, publisher):passclassPublisher:def__init__(self):self.subscriber=[]defaddSubscriber(self, sub):self.subscriber.append(sub)defremoveSubscriber(self,sub):self.subscriber.remove(sub)defnotify(self):for sub in self.subscriber:sub.update(self)classStaffPublisher(Publisher):def__init__(self, company_info=None):super().__init__()self.__company_info=company_info@propertydefcompany_info(self):return self.__company_info@company_info.setterdefcompany_info(self,info):self.__company_info=infoself.notify()classStaffSubcriber(Subscriber):def__init__(self):self.company_info=Nonedefupdate(self, publisher):self.company_info=publisher.company_infoprint("update val as: %s"% self.company_info)staffPub=StaffPublisher("initial info")print("---------initial------------")print(staffPub.company_info)
staffSub=StaffSubcriber()
staffPub.addSubscriber(staffSub)print("---------change info----------")
staffPub.company_info="go to work"
staffPub.company_info="you are good"
staffPub.company_info="but i will fire you"