一、观察者模式介绍
image.png二、观察者模式UML
image.png三、python实现观察者模式(demo1、2)
1、demo1
"""
"""
观察者模式
"""
class Subject(object):
def init(self):
self.__observers = []
def register(self, observer):
self.__observers.append(observer)
def notifyAll(self, *args, **kwargs):
for observer in self.__observers:
observer.notify(self, *args, **kwargs)
class Observer1(object):
def init(self, subject):
subject.register(self)
def notify(self, subject, *args):
print(type(self).__name__, ":: Got", args, "From", subject)
class Observer2(object):
def init(self, subject):
subject.register(self)
def notify(self, subject, *args):
print(type(self).__name__, ":: Got", args, "From", subject)
if name == "main":
subject = Subject()
observer1 = Observer1(subject)
observer2 = Observer2(subject)
subject.notifyAll('notification')
"""
2、demo2
"""
"""
观察者模式:新闻内容订阅和通知
"""
from abc import ABCMeta, abstractmethod
subject
class NewsPublisher(object):
def init(self):
self.__subscribers = []
self.__latestNews = None
def attach(self, subscriber):
self.__subscribers.append(subscriber)
def detach(self):
return self.__subscribers.pop()
def get_subscribers(self):
return [type(x).__name__ for x in self.__subscribers]
def notifySubscribers(self):
for sub in self.__subscribers:
sub.update()
def addNews(self, news):
self.__latestNews = news
def getNews(self):
return "Got News: ", self.__latestNews
observer
class Subscriber(metaclass=ABCMeta):
@abstractmethod
def update(self):
pass
class SMSSubscriber(Subscriber):
def init(self, publisher):
self.publisher = publisher
self.publisher.attach(self)
def update(self):
print(type(self).__name__, self.publisher.getNews())
class EmailSubscriber(Subscriber):
def init(self, publisher):
self.publisher = publisher
self.publisher.attach(self)
def update(self):
print(type(self).__name__, self.publisher.getNews())
class OtherSubscriber(Subscriber):
def init(self, publisher):
self.publisher = publisher
self.publisher.attach(self)
def update(self):
print(type(self).__name__, self.publisher.getNews())
client
if name == "main":
news_publisher = NewsPublisher()
for subscriber in [SMSSubscriber, EmailSubscriber, OtherSubscriber]:
subscriber(news_publisher)
print("\n Subscribers: ", news_publisher.get_subscribers())
news_publisher.addNews("Hello world! ")
news_publisher.notifySubscribers()
print("\n Detached: ", type(news_publisher.detach()).__name__)
print("\n Subscribers: ", news_publisher.get_subscribers())
news_publisher.addNews("Second News! ")
news_publisher.notifySubscribers()
"""
网友评论