观察者模式
观察者模式:
主题发布更新,订阅者收到通知,同步更新自己的业务,达到解耦的目的!
案例:报社发布报纸,订阅用户收到通知!
创建主题类接口(InterSubject.php)
<?php interface InterSubject { //注册订阅者 public function registerObserver(InterObserver $observer); //移除订阅者 public function removeObserver(InterObserver $observer); //订阅变更通知 public function notifyObserver(NotifyData $notifyData); }
创建主题实现类(Newspaper.php)
<?php class Newspaper implements InterSubject { private $observerList = []; //注册订阅 public function registerObserver( InterObserver $observer) { array_push($this->observerList,$observer); } //取消订阅 public function removeObserver(InterObserver $observer) { $observerList = $this->observerList; foreach ($observerList as $key=> $ob){ if($ob == $observer){ unset($observerList[$key]); } } $this->observerList = array_values($observerList); } public function notifyObserver(NotifyData $notifyData) { foreach ($this->observerList as $observer){ $observer->update($notifyData); } } }
创建订阅者接口(InterObserver.php)
<?php interface InterObserver { //观察者更新接口 public function update(NotifyData $notifyData); }
创建订阅者实现接口(UserA.php)
<?php class UserA implements InterObserver { public function update(NotifyData $notifyData) { echo 'I am A ,receive update!eventCode:'.$notifyData->eventCode."\n\r"; } }
创建订阅者实现接口(UserB.php)
<?php class UserB implements InterObserver { public function update(NotifyData $notifyData) { echo 'I am B ,receive update!eventCode:'.$notifyData->eventCode."\n\r"; } }
定义变更数据对象(NotifyData.php)
<?php class NotifyData { public $eventCode; public $eventName; public $eventData; }
定义启动入口(index.php)
<?php function __autoload($class){ if ($class) { $file = str_replace('\\', '/', $class); $file .= '.php'; if (file_exists($file)) { include $file; } } } //实例化主题 $newspager = new Newspaper(); $notifyData = new NotifyData(); //实例化订阅者 $userA = new UserA(); $userB = new UserB(); //订阅 $newspager->registerObserver($userA); $newspager->registerObserver($userB); //触发通知 $notifyData->eventCode='first eventCode'; $newspager->notifyObserver($notifyData); //取消订阅 $newspager->removeObserver($userA); $notifyData->eventCode='second eventCode'; //触发通知 $newspager->notifyObserver($notifyData);
启动


浙公网安备 33010602011771号