观察者模式

观察者模式

作者:LAMP小白  点击:1638  发布日期:2012-10-07 22:55:00  返回列表
当在程序中添加新功能后,这个程序就无法再次使用标准的升级包进行更新了,这是我们需要创建一个插件系统,在不影响核心代码的情况下,添加新功能,这时就可以用观察者模式了.
他能够更便利的创建查看目标对象状态的对象,并且提供与核心对象非耦合的指定功能性

基于观察者模式设计的核心对象负责向被指派观察和理解核心对象的其他类传达发生了哪些状态变化,其他观察者类可以采取外部动作,也可以更改核心对象

和中介者模式类似也会触发一个通知其他类的方法,不过不同的是,中介者可以相互触发,而观察者类只能接受不能主动触发

mio_lt;?php
    //一个核心的类
    class cd
    {
        public $title = '';
        public $band = '';
        protected $_observers = array();
        public function __construct($title, $band)
        {
            $this-mio_gt;title = $title;
            $this-mio_gt;band = $band;
        }
        public function attachObserver($type, $observer)
        {
            $this-mio_gt;_observers[$type][] = $observer;
        }
        public function notifyObserver($type)
        {
            if(isset($this-mio_gt;_observers[$type])){
                foreach($this-mio_gt;_observers[$type] as $observer)
                    $observer-mio_gt;update($this);
            }
        }
        public function buy()
        {
            //...
            $this-mio_gt;notifyObserver('purchased');
        }
    }
    //观察者类
    class buyCDNotifyStreamObserver
    {
        public function update(cd $cd)
        {
            $activity = "the cd named {$cd-mio_gt;title} by";
            $activity .= "{$cd-mio_gt;band} was just purchased";
            activityStram::addNewItem($activity);
        }
    }
    //配合观察者类执行实际动作的类
    class activityStream
    {
        public static function addNewItem($item)
        {
            echo $item;
        }
    }
    //创建一个CD实例
    $title = 'waste of a Rib';
    $band = 'Never Again';
    $cd = new cd($title, $band);
    //实例化观察者对象
    $observer  =new buyCDNotifyStreamObserver();
    //将他添加到cd的观察者列表
    $cd-mio_gt;attachObserver('purchased', $observer);
    $cd-mio_gt;buy();
?mio_gt;



上一篇:中介者模式 下一篇:快递查询API
0