python 设计模式(六) 观察者模式(Observer pattern)

观察者模式即当被观察对象发生变化时,能及时通知观察者,这种需求主要用在网站或者店铺的关注上,比如你关注了某个微信公众号,或者淘宝上的商家,当公众号有更新或者店家新到商品或者商品促销时,可以及时通知你。

代码实现了E_commerce被观察对象基类。主要实现了属性_observers和方法add_observer(注册观察者),delete_observer(注销观察者), notify_all_observers(通知所有观察者)。实现了A_shop类,继承自E_commerce。A_shop包含promotion(促销活动列表)。当进行促销时,会把消息发送给所有关注这家店铺的消费者。实现了Observer抽象类,其有必须实现的方法update。实现了A_customer, B_customer两个继承自Observer抽象类的观察者类。当店铺做新的促销活动时,会把self和促销活动传递给观察者的update方法。update方法具体如下:

import abc


class E_commerce(object):
    """
    电商基类,实现了注册,注销观察者,通知所有观察者方法
    """
    def __init__(self):
        self._observers = []

    def add_observer(self, observer):
        if observer not in self._observers:
            self._observers.append(observer)

    def delete_observer(self, observer):
        if observer in self._observers:
            self._observers.remove(observer)
        else:
            raise Exception('%s observer not be monitored' % observer)

    def notify_all_observers(self, promotion):
        for observer in self._observers:
            observer.update(self, promotion)


class A_shop(E_commerce):
    """
    A电商, 被观察对象
    """
    def __init__(self):
        super(A_shop, self).__init__()
        self._promotion = [] # 促销活动列表

    def __str__(self):
        return 'A_电商'

    @property
    def promotion(self):
        """返回所有促销活动"""
        return self._promotion

    @promotion.setter
    def promotion(self, promotion):
        self._promotion.append(promotion) # 添加新的促销活动
        self.notify_all_observers(promotion) # 把新促销活动信息发送给关注店铺的人(观察者)


class Observer(object):
    """
    观察者抽象基类,实现了更新方法
    """
    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod
    def update(self, *args, **kwargs):
        pass


class A_customer(Observer):
    """
    A客户实现了update方法
    """
    def update(self, e_commerce, promotion):
        print('to a_customer: %s正在%s' % (e_commerce, promotion))


class B_customer(Observer):
    """
    A客户实现了update方法
    """
    def update(self, e_commerce, promotion):
        print('to b_customer: %s正在%s' % (e_commerce, promotion))


if __name__ == '__main__':
    a_customer = A_customer()
    b_customer = B_customer()
    a_shop = A_shop()
    a_shop.add_observer(a_customer) # 注册
    a_shop.add_observer(b_customer) # 注册
    a_shop.promotion = '大减价'
    a_shop.promotion = '清仓大处理'
    a_shop.delete_observer(a_customer)
    a_shop.promotion = '大出血'

结果如下

to a_customer: A_电商正在大减价
to b_customer: A_电商正在大减价
to a_customer: A_电商正在清仓大处理
to b_customer: A_电商正在清仓大处理
to b_customer: A_电商正在大出血

由结果知,对a_customer进行注销后,后面的促销活动,就不通知a_customer了

    原文作者:ruguowoshiyu
    原文地址: https://blog.csdn.net/ruguowoshiyu/article/details/80851446
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞