Design pattern-behavior-observer pattern (publish and subscribe pattern)

Chain of Responsibility Model

Overview

  • Define a one-to-many dependency relationship between objects. When the state of an object changes, all objects that depend on it are notified and automatically updated. Publish-subscribe model

Object

  • Abstract subject (Subject)
  • Concrete Subject (ConcreteSubject)-Publisher
  • Abstract Observer (Observer)
  • Concrete Observer (ConcreteObserver)-Subscriber

Applicable scene

  • When an abstract model has two aspects, one aspect depends on the other. Encapsulate the two in two independent objects so that they can be changed and reused independently
  • When a change to an object needs to change other objects at the same time, it is not known how many objects need to be changed
  • When an object must notify other objects, and he cannot assume who the other objects are, in other words, you don’t want these objects to be tightly coupled

example

from abc import ABCMeta, abstractmethod

# 抽象订阅者
class Observer(metaclass=ABCMeta):
    @abstractmethod
    def update(self, notice):
        pass

# 抽象发布者
class Notice:
    def __init__(self):
        self.observers = []
    
    def attach(self, obs):
        self.observers.append(obs)
    
    def detach(self, obs):
        self.observers.remove(obs)
    
    def notify(self):
        for obs in self.observers:
            obs.update(self)
    

# 发布者
class StaffNotice(Notice):
    def __init__(self, info):
        super().__init__()
        self.__info = info 
    
    @property
    def info(self):
        return self.__info
    
    @info.setter
    def info(self, info):
        self.__info = info
        self.notify()

#订阅者
class Staff(Observer):
    def __init__(self):
        self.info = None
        self.notice = None

    def subscribe(self, notice):
        self.notice = notice
        notice.attach(self)
    
    def unsubscribe(self):
        if not self.notice:
            return
        self.notice.detach(self)
        self.notice = None

    def update(self, notice):
        self.info = notice.info
    
    def __str__(self):
        return self.info

# client
staff_notice = StaffNotice("初始化信息")
staff1 = Staff()
staff2 = Staff()
staff1.subscribe(staff_notice)
staff2.subscribe(staff_notice)
staff_notice.info = "更新消息: 公司放假了!!!!"

print(str(staff1))
print(str(staff2))

staff1.unsubscribe()
staff_notice.info = "更新消息: 公司又不放假了!!!!"
print(str(staff1))
print(str(staff2))

advantage

  • The degree of abstract coupling between the target and the observer is minimal
  • Support broadcast communication

Guess you like

Origin blog.csdn.net/DALAOS/article/details/114127854