[DesignPattern]Observer Pattern (Python)

周五听峰哥说java的设计模式,于是看看python的实现,理解下。

简单的实现观察者模式。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# observer_simple.py

# Date: 2014-03-16
# CopyRight: orangleliu@gmail.com
# Lisence: BSD
# tips:简单实现观察者模式


class Subject(object):
    '''
    Subject has three methods:
    add_observer
    delete_observer
    notify
    '''
    def __init__(self):
        self.observers_list = []

    def add_observer(self, obs):
        if obs is not self.observers_list:
            self.observers_list.append(obs)

    def delete_observer(self, obs):
        try:
            self.observers_list.remove(obs)
        except ValueError:
            pass

    def notify(self):
        for obs in self.observers_list:
            obs.notify()

class Observer(object):
    def __init__(self, name):
        self.name = name

    def notify(self):
        print "%s accept the infomation" %self.name

if __name__=='__main__':
    ob1 = Observer('Java')
    ob2 = Observer('Python')

    sub = Subject()
    sub.add_observer(ob1)
    sub.add_observer(ob2)
    print 'Tow users'
    sub.notify()
    print 'One user'
    sub.delete_observer(ob1)
    sub.notify()

'''
console:

PS D:\code\python\python_abc\design_pattern> python .\observer_simple.py
Tow users
Java accept the infomation
Python accept the infomation
One user
Python accept the infomation

quote:
    https://github.com/jfcalvo/patterns/blob/master/python/observer.py
    http://code.activestate.com/recipes/131499-observer-pattern/
'''




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值