欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

PHP 观察者设计模式测试代码笔记

程序员文章站 2022-06-01 08:37:57
...
';    }}/** * 观察者2 * Class SaveName */class SaveName implements Observer {    public function update()    {        echo 'the name has been save 
'; }}/** * 被观察者接口 * Interface Observered */interface Observered { public function attach($object); public function delete($object); public function notify();}/** * 被观察者 * Class User */class User implements Observered { public $observers = array(); /** * 注册观察者 * @param $object */ public function attach($object) { if (!is_object($object)) { exit('it is not an object'); } if ($object instanceof Observer) { if (!in_array($object,$this->observers)) { $this->observers[] = $object; } } else { echo get_class($object) . ' is disable
'; } } /** * 删除观察者 * @param $object */ public function delete($object) { if (in_array($object,$this->observers)) { $index = array_search($object,$this->observers); unset($this->observers[$index]); } } /** * 通知所有观察者 */ public function notify() { foreach ($this->observers as $val) { $val->update(); } } /** * 被观察者自己的业务 */ public function printName() { echo 'I have been observing
'; }} $object = new User(); $object->attach(new SendEmail()); //注册观察者1 $object->attach(new SaveName()); //注册观察者2 $object->printName(); //被观察者自己的业务 $object->notify(); //通知所有的观察者