Observer 观察者
最后更新于:2022-04-02 02:26:33
[TOC]
## 实例
```
class User implements splsubject{
/**
* 观察者列表
* @var SplObjectStorage
*/
protected $observer;
public function __construct()
{
$this->observer = new SplObjectStorage();
}
public function login()
{
$this->notify();
echo 'login complete \n';
}
public function success(){
echo "success\n";
}
public function attach(SplObserver $observer)
{
$this->observer->attach($observer);
}
public function detach(SplObserver $observer)
{
$this->observer->detach($observer);
}
public function notify()
{
$this->observer->rewind();
while ($this->observer->valid())
{
$observer = $this->observer->current();
$observer->update($this);
$this->observer->next();
}
}
}
class Cat implements SplObserver{
public function update(SplSubject $subject)
{
$subject->success();
}
}
class Dog implements SplObserver{
public function update(SplSubject $subject)
{
$subject->success();
}
}
$cat = new Cat();
$dog = new Dog();
$user = new User();
$user->attach($cat);
$user->attach($dog);
$user->login();
```
';