标签:reac replace 观察 rem rac design for IV protect
github地址:https://github.com/ZQCard/design_pattern
/** * 当对象间存在一对多关系时,则使用观察者模式(Observer Pattern)。 * 比如,当一个对象被修改时,则会自动通知它的依赖对象。观察者模式属于行为型模式。 * 一个对象(目标对象)的状态发生改变,所有的依赖对象(观察者对象)都将得到通知,进行广播通知。 */
(1) Subject.class.php(目标类)
<?php namespace Observer; class Subject { private $state; private $observers = []; public function getState() { return $this->state; } public function seState($state) { $this->state = $state; $this->notifyAllObjects(); } public function register(Observer $object) { $this->observers[] = $object; } public function remove($object) { foreach ($this->observers as $key => $observer) { if ($observer == $object){ unset($this->observers[$key]); } } } public function notifyAllObjects() { foreach ($this->observers as $observer) { $observer->update(); } } }
(2)Observer.class.php(观察者抽象父类)
<?php namespace Observer; abstract class Observer { protected $subject; public abstract function update(); }
(3)ObjectA.class.php (具体抽象类A)
<?php namespace Observer; class ObserverA extends Observer { private $myState = ‘init A‘; public function __construct(Subject $subject) { $this->subject = $subject; $this->subject->register($this); } public function update() { $this->myState = $this->subject->getState(); } public function getSate() { return "ObserverA get state:".$this->myState; } }
(4)ObserverB.class.php(具体观察者B)
<?php namespace Observer; class ObserverB extends Observer { private $myState = ‘init B‘; public function __construct(Subject $subject) { $this->subject = $subject; $this->subject->register($this); } public function update() { $this->myState = $this->subject->getState(); } public function getSate() { return "ObserverB get state:".$this->myState; } }
(5)observer.php
<?php spl_autoload_register(function ($className){ $className = str_replace(‘\\‘,‘/‘,$className); include $className.".class.php"; }); use Observer\ObserverA; use Observer\ObserverB; use Observer\Subject; /*
ObserverA get state:init A
ObserverB get state:init B
ObserverA get state:hello
ObserverB get state:hello
*/
$subject = new Subject(); $objectA = new ObserverA($subject); $objectB = new ObserverB($subject); echo $objectA->getSate(); echo ‘<br/>‘; echo $objectB->getSate(); echo ‘<br/>‘; $subject->seState("hello"); echo $objectA->getSate(); echo ‘<br/>‘; echo $objectB->getSate(); echo ‘<br/>‘;
标签:reac replace 观察 rem rac design for IV protect
原文地址:https://www.cnblogs.com/zhouqi666/p/9164450.html