php设计模式之观察者模式

观察者模式:能够更便利地创建查看目标对象状态的对象,并且提供与核心对象非耦合的指定功能性。

利用这种模式可以方便地创建一个对象(观察者),其可以用来“监视”另一个对象(被观察者)的状态。这样,就可以在不必完全重构某些核心对象(可以理解成被观察者)的情况下,向现有的应用层序填加额外的功能。

即是动态创建对象(观察者),根据被观察者的状态动态调用观察者动作行为。

1. 被观察者 添加观察者,(attach)

2. 根据被观察者动态调用观察者的行为,即运行观察者。(notify)

 

 

一、php库中定义的接口splSubject  splObserver

<?php
class Subject implements SplSubject {
    protected $_value;
    protected $_observers;
    public function __construct() {
        $this->_observers = new SplObjectStorage ();
    }
    public function attach(SplObserver $object) {
        $this->_observers->attach ( $object );
    }
    public function detach(SplObserver $object) {
        $this->_observers->detach ( $object );
    }
    public function notify() {
        foreach ( $this->_observers as $object ) {
            $object->update ( $this );
        }
    }
    public function setValue($value) {
        $this->_value = $value;
        $this->notify ();
    }
    public function getValue() {
        return $this->_value;
    }
}
class Observer implements SplObserver {
    public function update(SplSubject $subject) {
        var_dump ( "最后更新时间为:" . $subject->getValue () );
    }
}

date_default_timezone_get ( 'Asia/Shanghai' );

error_reporting ( E_ALL );
$subject = new Subject ();
$observer = new Observer ();
$subject->attach ( $observer );
$subject->setValue ( date( 'Y-m-d H:i:s' ), time () );


二 .自定义观察者模式

<?php
class order {

    protected $observers = array(); // 存放观察容器
     
    //观察者新增
    public function addObServer($type, $observer) {
        
        $this->observers[$type][] = $observer;
    }
    

    //运行观察者
    public function obServer($type) {
        if (isset($this->observers[$type])) {
            foreach ($this->observers[$type] as $obser) {
                $a = new $obser;
                $a->update($this); //公用方法
            }
        }
    }
     
    //下单购买流程
    public function create() {
        echo '购买成功';
        $this->obServer('buy'); // buy动作
    }
}

class orderEmail {
    public static function update($order) {
        echo '发送购买成功一个邮件';
    }
}
class orderStatus {
    public static function update($order) {
        echo '改变订单状态';
    }
}
$ob = new order;
$ob->addObServer('buy', 'orderEmail');
$ob->addObServer('buy', 'orderStatus');
$ob->create();

 

posted @ 2013-08-30 11:44  北斗极星  阅读(338)  评论(0编辑  收藏  举报