博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python设计模式之观察者模式
阅读量:4649 次
发布时间:2019-06-09

本文共 1622 字,大约阅读时间需要 5 分钟。

观察者模式

 当对象间存在一对多关系时,则使用观察者模式(Observer Pattern)。比如,当一个对象被修改时,则会自动通知它的依赖对象。观察者模式属于行为型模式。

 观察者模式在状态检测和事件处理等场景中是非常有用的。这种模式确保一个核心对象可以由一组未知并可能正在扩展的“观察者”对象来监控。一旦核心对象的某个值发生变化,它通过调用update()函数让所有观察者对象知道情况发生了变化。各个观察者在核心对象发生变化时,有可能会负责处理不同的任务;核心对象不知道也不关心这些任务是什么,通常观察者也同样不知道,不关心其他的观察者正在做什么。

class Inventory:    """docstring for ClassName"""    def __init__(self):        self.observers=[]        self._product=None        self._quantity=0    def attach(self,observer):        self.observers.append(observer)    @property    def product(self):        return self._product    @product.setter    def product(self,value):        self._product=value        self._update_observers()    @property    def quantity(self):        return self._quantity    @quantity.setter    def quantity(self,value):        self._quantity=value        self._update_observers()    def _update_observers(self):        for observer in self.observers:            observer()    class ConsoleObserver:                """docstring for ConsoleObserver"""                def __init__(self, Inventory):                    self.Inventory=Inventory                def __call__(self):                    print(self.Inventory.product)                    print(self.Inventory.quantity)
>>> import ObserverPatternDemo>>> i=ObserverPatternDemo.Inventory()>>> c=ObserverPatternDemo.ConsoleObserver(i)>>> i.attach(c)>>> i.product="Hello world!"Hello world!0>>> i.quantity=999Hello world!999

这个对象两个属性,对其执行赋值,便调用_update_observers方法。该方法所做的工作就是对所有可用的观察者进行遍历,好让他们知道发生了一些变化。这里直接调用__call__函数来处理变化。这在其他许多编程语言是不能的,在python中是一种让我们代码可读性的一种捷径。

 

转载于:https://www.cnblogs.com/SamllBaby/p/5428050.html

你可能感兴趣的文章
[转]【HttpServlet】HttpServletResponse接口 案例:完成文件下载
查看>>
Eclipse配置默认的编码集为utf-8
查看>>
初学Python
查看>>
坑:Office Tool Plus在干啥呀
查看>>
[转]EXCEL截取字符串中某几位的函数——LeftMIDRight及Find函数的使用
查看>>
rman 脚本备份全过程
查看>>
图像处理笔记(十八):模板匹配
查看>>
Educational Codeforces Round 60 D. Magic Gems
查看>>
c# 保存和打开文件的方法
查看>>
调用图灵机器人API实现简单聊天
查看>>
MATLAB indexing question
查看>>
MATLAB 求解最优化问题
查看>>
【转载】java InputStream读取数据问题
查看>>
网络基础Cisco路由交换四
查看>>
CloudFoundry基础知识之理论篇
查看>>
fatal error LNK1120: 11 unresolved externals
查看>>
测试工具类汇总
查看>>
WEB消息推送-comet4j
查看>>
安卓开发 数据存储
查看>>
贪心思维 专题记录 2017-7-21
查看>>