日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【编程思想】【设计模式】【行为模式Behavioral】观察者模式Observer

發(fā)布時間:2023/12/18 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【编程思想】【设计模式】【行为模式Behavioral】观察者模式Observer 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

Python轉載版

?

https://github.com/faif/python-patterns/blob/master/behavioral/observer.py

#!/usr/bin/env python # -*- coding: utf-8 -*-""" http://code.activestate.com/recipes/131499-observer-pattern/*TL;DR80 Maintains a list of dependents and notifies them of any state changes. """from __future__ import print_functionclass Subject(object):def __init__(self):self._observers = []def attach(self, observer):if observer not in self._observers:self._observers.append(observer)def detach(self, observer):try:self._observers.remove(observer)except ValueError:passdef notify(self, modifier=None):for observer in self._observers:if modifier != observer:observer.update(self)# Example usage class Data(Subject):def __init__(self, name=''):Subject.__init__(self)self.name = nameself._data = 0@propertydef data(self):return self._data@data.setterdef data(self, value):self._data = valueself.notify()class HexViewer:def update(self, subject):print(u'HexViewer: Subject %s has data 0x%x' %(subject.name, subject.data))class DecimalViewer:def update(self, subject):print(u'DecimalViewer: Subject %s has data %d' %(subject.name, subject.data))# Example usage... def main():data1 = Data('Data 1')data2 = Data('Data 2')view1 = DecimalViewer()view2 = HexViewer()data1.attach(view1)data1.attach(view2)data2.attach(view2)data2.attach(view1)print(u"Setting Data 1 = 10")data1.data = 10print(u"Setting Data 2 = 15")data2.data = 15print(u"Setting Data 1 = 3")data1.data = 3print(u"Setting Data 2 = 5")data2.data = 5print(u"Detach HexViewer from data1 and data2.")data1.detach(view2)data2.detach(view2)print(u"Setting Data 1 = 10")data1.data = 10print(u"Setting Data 2 = 15")data2.data = 15if __name__ == '__main__':main()### OUTPUT ### # Setting Data 1 = 10 # DecimalViewer: Subject Data 1 has data 10 # HexViewer: Subject Data 1 has data 0xa # Setting Data 2 = 15 # HexViewer: Subject Data 2 has data 0xf # DecimalViewer: Subject Data 2 has data 15 # Setting Data 1 = 3 # DecimalViewer: Subject Data 1 has data 3 # HexViewer: Subject Data 1 has data 0x3 # Setting Data 2 = 5 # HexViewer: Subject Data 2 has data 0x5 # DecimalViewer: Subject Data 2 has data 5 # Detach HexViewer from data1 and data2. # Setting Data 1 = 10 # DecimalViewer: Subject Data 1 has data 10 # Setting Data 2 = 15 # DecimalViewer: Subject Data 2 has data 15 Python轉載版

?

轉載于:https://www.cnblogs.com/demonzk/p/9035645.html

總結

以上是生活随笔為你收集整理的【编程思想】【设计模式】【行为模式Behavioral】观察者模式Observer的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內容還不錯,歡迎將生活随笔推薦給好友。