当前位置:Gxlcms > PHP教程 > PHP观察者设计模式测试代码笔记

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

时间:2021-07-01 10:21:17 帮助过:20人阅读

';    }}/** * 观察者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(); //通知所有的观察者

人气教程排行