Пример #1
0
}
//实现可被观察对象
//负责维护关注列表,并发送消息
class UserList implements IObservable
{
    private $_observers = array();
    public function addCustomer($name)
    {
        foreach ($this->_observers as $obs) {
            $obs->onChanged($this, $name);
        }
    }
    public function addObserver($observer)
    {
        $this->_observers[] = $observer;
    }
}
//实现一个观察者
class UserListLogger implements IObserver
{
    public function onChanged($sender, $args)
    {
        echo "'{$args}' added to user list\n";
    }
}
$ul = new UserList();
//观察者列表
$ul->addObserver(new UserListLogger());
//添加观察者至观察者列表
$ul->addCustomer("Jack");
//添加用户,并将消息发送给观察者
    {
        echo "'{$args}' send to UserListLogger\n";
    }
    public function getName()
    {
        return 'UserListLogger';
    }
}
class OtherObserver implements IObserver
{
    public function onSendMsg($sender, $args)
    {
        echo "'{$args}' send to OtherObserver\n";
    }
    public function getName()
    {
        return 'OtherObserver';
    }
}
$ul = new UserList();
//被观察者
$ul->addObserver(new UserListLogger());
//增加观察者
$ul->addObserver(new OtherObserver());
//增加观察者
$ul->sendMsg("Jack");
//发送消息到观察者
$ul->removeObserver('UserListLogger');
//移除观察者
$ul->sendMsg("hello");
//发送消息到观察者