行为型设计模式: 观察者模式 observer
当对象的状态发生变化时,所有依赖于它的对象都得到通知并被自动更新。它使用的是低耦合的方式。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| <?php
interface Observer { public function update(Subject $subject): void; }
class ConcreteObserver implements Observer { private $observerState = ''; function update(Subject $subject): void { $this->observerState = $subject->getState(); echo '执行观察者操作!当前状态:' . $this->observerState; } }
class Subject { private $observers = []; private $stateNow = ''; public function attach(Observer $observer): void { array_push($this->observers, $observer); } public function detach(Observer $observer): void { $position = 0; foreach ($this->observers as $ob) { if ($ob == $observer) { array_splice($this->observers, ($position), 1); } ++$position; } } public function notify(): void { foreach ($this->observers as $ob) { $ob->update($this); } } }
class ConcreteSubject extends Subject{ public function setState($state) { $this->stateNow = $state; $this->notify(); }
public function getState() { return $this->stateNow; } }
|
可以在 Subject
里仅注重其本身的业务逻辑, 对于观察者模式下对观察者的notify 操作改为 implement 一个接口来实现, 使其 observable ?
SPL扩展实现观察者模式-完整源码:
https://github.com/zhangyue0503/designpatterns-php/blob/master/06.observer/source/spl_observer.php