PHP-设计模式-观察者模式

观察者模式:一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。
1:定义一个项目subjects抽象类 ,一个观察者observers抽象类。
subject 实现三个方法,1,添加add ,删除:remove ,通知 :notify。
observe 实现update 方法
格式和组合模式有点类似。

<!DOCTYPE html> 
<html> 
<body> 
<?php 
header("Content-type: text/html; charset=utf-8");
abstract class subjects{
    function add(observers $observer){}
    function remove(observers $observer){}
    function notify(){}
}
abstract class observers{
    function update(){}
}
class subject extends subjects{
    public $arr = array();
    function add(observers $observer){
        array_push($this->arr,$observer);
    }
    function remove(observers $observer){
        $a = array_search($observer,$this->arr);
        unset($this->arr[$a]);
    }
    function notify(){  
        foreach($this->arr as $a){
            $a->update();
        }
    }
}
class observe extends observers{
    public $name = null;
    function __construct($str){
        $this->name = $str;
    }
    function update(){
        echo "{$this->name}observer";
    }
}
$a = new observe('我是第一个');
$b = new observe('我是第二个');
$ob = new subject();

$ob->add($a);
$ob->add($b);
$ob->remove($a);
$ob->notify();
//输出  我是第二个observer
?> 

</body> 
</html>

猜你喜欢

转载自blog.csdn.net/qq_36211859/article/details/82347252