实例
<?php /** * @Description: 观察者模式 * @Author: luoxiaojin * @Date: 2020-06-29 15:28:37 * @LastEditors: luoxiaojin * @LastEditTime: 2020-06-29 16:19:34 * @FilePath: \design_patterns\l5.php */ // 观察者 SplObserver,被观察者 SplSubject class user implements SplSubject{ public $loginNum = 0; public $hobbys = ['reading','singing','sporting','running','eating','study','codeing']; public $hobby; private $obStorage; public function __construct(){ $this->loginNum = rand(1,10); $this->hobby = $this->hobbys[rand(0,count($this->hobbys)-1)]; $this->obStorage = new SplObjectStorage(); } public function login(){ sleep(0.5); $this->notify(); } public function attach(\SplObserver $observer){ $this->obStorage->attach($observer); } public function detach(\SplObserver $observer){ $this->obStorage->detach($observer); } public function notify(){ $this->obStorage->rewind(); while ($this->obStorage->valid()) { $this->obStorage->current()->update($this); $this->obStorage->next(); } } } class SafeCener implements SplObserver{ public function update(\SplSubject $subject){ var_dump($subject->loginNum); } } class AdCenter implements SplObserver{ public function update(\SplSubject $subject){ var_dump($subject->hobby); } } // 实施观察 $user = new user(); $obs1 = new SafeCener(); $obs2 = new AdCenter(); $user->attach($obs1); $user->attach($obs2); $user->login();
运行实例 »
点击 "运行实例" 按钮查看在线实例
——学习参考与 bilibili燕十八 面向对象与设计模式