python设计模式:观察者模式
前言
要学好编程,或者说是软件开发,学好设计模式也是重要的一关(亲身体会!!!对于框架少的一些小众语言得自己去搭框架,不论开发还是维护,还是很费劲得),即便是有很多现成的框架可以使用,学好设计模式对框架优化或性能提升还是有帮助得。下面开始学习python下得观察者模式。

一、观察者模式是什么?
观察者模式属于行为模式,核心包含观察者(Subject)、被观察者(Observer),用于一对多的场景,当要将数据发给多个目标时,通过被观察者,它会发送给所有观察者。

核心方法:
- 观察者:数据发布方法 update()
- 被观察者:
数据订阅方法 attach()
取消订阅方法 detach()
数据通知 notify()
由于数据的发布的对像可能不止一个、数据的观察者(关注者)的对像也不同,因此观察者模式也比设计为:被观察者接口(SubjectInterface)、具体观察者对像(Subject)、观察者接口(ObserverInterface)、具体观察者(Observer)。
一个典型的应用就是发布-订阅模型。
二、Python中观察者模式实现
1.引入库
在Python里面设计接口用到abc(abstract base classes,ABCs)模块,用到元类ABCMeta和abstractmethod方法,继承抽象类的对像必须实现abstractmethod装饰的方法。
from abc import ABCMeta, abstractmethod
class Interface(metaclass=ABCMeta):
@abstractmethod
def func(self):
pass
class ConcreateInterface(Interface):
def func(self):
print("实现接口方法")
2.观察者模式在python实现
(1)观察者接口
from abc import ABCMeta, abstractmethod
# 观察者接口
class ObserverInterface(metaclass=ABCMeta):
@abstractmethod
def update(self, subject, message):
pass
(2)观察对像
# 观察对像
class SubjectInterface:
@abstractmethod
def attach(self, observer):
pass
@abstractmethod
def detach(self, observer):
pass
@abstractmethod
def notify(self, message):
pass
(3)具体被观察对像
class ConcreateSubject(SubjectInterface):
def __init__(self):
self._observers = []
def attach(self, observer):
self._observers.append(observer)
def detach(self, observer):
self._observers.remove(observer)
def

最低0.47元/天 解锁文章
301

被折叠的 条评论
为什么被折叠?



