码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式-行为型模式,观察者模式(13)

时间:2018-03-08 02:35:47      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:format   __name__   使用   post   server   hex   对象   color   依赖   

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

有时,我们希望在一个对象的状态改变时更新另外一组对象。

 

class Publisher:

    def __init__(self):
        self.observers = []

    def add(self, observer):
        if observer not in self.observers:
            self.observers.append(observer)
        else:
            print(Failed to add: {}.format(observer))

    def remove(self, observer):
        try:
            self.observers.remove(observer)
        except ValueError:
            print(Failed to remove: {}.format(observer))

    def notify(self):
        [o.notify(self) for o in self.observers]


class DefaultFormatter(Publisher):

    def __init__(self, name):
        Publisher.__init__(self)
        self.name = name
        self._data = 0

    def __str__(self):
        return "{}: ‘{}‘ has data = {}".format(type(self).__name__, self.name, self._data)

    @property
    def data(self):
        return self._data

    @data.setter
    def data(self, new_value):
        try:
            self._data = int(new_value)
        except ValueError as e:
            print(Error: {}.format(e))
        else:
            self.notify()


class HexFormatter:

    def notify(self, publisher):
        print("{}: ‘{}‘ has now hex data = {}".format(type(self).__name__,
                                                      publisher.name, hex(publisher.data)))


class BinaryFormatter:

    def notify(self, publisher):
        print("{}: ‘{}‘ has now bin data = {}".format(type(self).__name__,
                                                      publisher.name, bin(publisher.data)))


def main():
    df = DefaultFormatter(test1)
    print(df)

    print()
    hf = HexFormatter()
    df.add(hf)
    df.data = 3
    print(df)

    print()
    bf = BinaryFormatter()
    df.add(bf)
    df.data = 21
    print(df)

    print()
    df.remove(hf)
    df.data = 40
    print(df)

    print()
    df.remove(hf)
    df.add(bf)
    df.data = hello
    print(df)

    print()
    df.data = 15.8
    print(df)

if __name__ == __main__:
    main()

 

设计模式-行为型模式,观察者模式(13)

标签:format   __name__   使用   post   server   hex   对象   color   依赖   

原文地址:https://www.cnblogs.com/ydf0509/p/8526100.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!