PHP设计模式 - 观察者模式
in PHP with 0 comment

PHP设计模式 - 观察者模式

in PHP with 0 comment

观察者模式类图

<?php
/**
 * @Author: Cizel
 * @Date:   2016-04-07 16:49:03
 * @Last Modified by:   Cizel
 * @Last Modified time: 2016-04-07 18:10:15
 */

interface Subject{
    public function addObserver($observer);
    public function deleteObserver($observer);
    public function notifyObserver();
}
<?php
/**
 * @Author: Cizel
 * @Date:   2016-04-07 16:54:35
 * @Last Modified by:   Cizel
 * @Last Modified time: 2016-04-07 18:37:12
 */

class ConcreteSubject implements Subject{
    private $observerList;
    public function __construct(){
        $this->observerList = null;
    }
    public function getObserverList(){
        return $this->observerList;
    }
    public function addObserver($observer){
        if($this->observerList==null || in_array($observer, $this->observerList,true) == false){
            $this->observerList[] = $observer;
        }
    }
    public function deleteObserver($observer){
        if(($key = array_search($observer,$this->observerList)) !==false){
            unset($this->observerList[$key]);
        }
    }
    public function notifyObserver(){
        foreach ($this->observerList as $key => $value) {
            $value->update();
        }
    }

}
<?php
/**
 * @Author: Cizel
 * @Date:   2016-04-07 17:09:03
 * @Last Modified by:   Cizel
 * @Last Modified time: 2016-04-07 18:14:30
 */

class ConcreteObserver implements Observer{
    private $subject;
    public function __construct($subject){
        $this->subject = $subject;
        $this->subject->addObserver($this);
    }
    public function update(){
        echo  "res update <br />";
    }
}
<?php
/**
 * @Author: Cizel
 * @Date:   2016-04-07 17:10:54
 * @Last Modified by:   Cizel
 * @Last Modified time: 2016-04-07 18:27:34
 */
function __autoload($classname) {
    require_once($classname.".php");
}
$center = new ConcreteSubject();
$observer1 = new ConcreteObserver();
$observer2 = new ConcreteObserver();
$center->notifyObserver();
echo "delete 1 <br />";
$center->deleteObserver($observer2);
$center->notifyObserver();

  笔者在校期间都是使用强类型的语言 C++/Java 等去实现算法和数据结构,现在写php感到很是不习惯。感觉php类面向对象,调试程序的时候非常麻烦。不知道 xdebug 可不可以解决这个问题。

Responses