笔记5:观察者模式


class Observed implements \SplSubject
{

    private $_observers = [];
    private $_name;

    public function __construct($name)
    {
        $this->_observers = new SplObjectStorage();
        $this->_name = $name;
    }

    public function attach(\SplObserver $observer)
    {
        $this->_observers->attach($observer);
    }

    public function detach(\SplObserver $observer)
    {
        $this->_observers->detach($observer);
    }

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

class Observer1 implements \SplObserver
{

    public function update(\SplSubject $observed)
    {
        echo __CLASS__ . "收到通知!\n";
    }
}

class Observer2 implements \SplObserver
{

    public function update(\SplSubject $observed)
    {

        echo __CLASS__ . "收到通知!\n";
    }
}


$ff = new Observed("Jay");

// 添加监听者
$observer1 = new Observer1;
$ff->attach($observer1);

$observer2 = new Observer2;
$ff->attach($observer2);

// 通知被监听者
$ff->notify();

echo "---\n";

// 取消被监听者
$ff->detach($observer1);

// 通知被监听者
$ff->notify();