设计模式之观察者模式(php实现)
Posted 周起
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设计模式之观察者模式(php实现)相关的知识,希望对你有一定的参考价值。
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 ObserverObserverA; use ObserverObserverB; use ObserverSubject; /*
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/>‘;
以上是关于设计模式之观察者模式(php实现)的主要内容,如果未能解决你的问题,请参考以下文章