php模式设计之 观察者模式

所谓模式,更多的是一种想法,完全没必要拘泥于代码细节。观察者模式更多体现了两个独立的类利用接口完成一件本应该很复杂的事情。不利用主题类的话,我们还需要不断循环创建实例,执行操作。而现在只需要创建实例就好,执行操作的事儿只需要调用一次通知的方法就好啦。

<?php
header("Content-type:text/html;charset=utf-8");

//主题接口
interface Subject
{
    public function register(Observer $observer);
    public function notify();
}

//观察者接口
interface Observer
{
    public function watch();
}

//主题
class Action implements Subject
{
    public $_observers = [];
    public function register(Observer $observer) {
        $this->_observers[] = $observer;
    }

    public function notify()
    {
        foreach ($this->_observers as $observer) {
            $observer->watch();
        }
    }
}

//观察者
class Cat implements Observer
{
    public function watch()
    {
        echo "Cat watches TV<hr/>";
    }
}
class Dog implements Observer
{
    public function watch()
    {
        echo 'Dog watches TV<hr/>';
    }
}
class People implements Observer
{
    public function watch()
    {
        echo 'People watches TV<hr/>';
    }
}

$action = new Action();
$action->register(new Cat());
$action->register(new People());
$action->register(new Dog());
$action->notify();

正因为来之不易,所以才有了后来的倍加珍惜。
原文地址:https://www.cnblogs.com/jjxhp/p/9933948.html