<?php abstract class Subject { private $_observers = array(); public function attach(Observer $observer) { $this->_observers[] = $observer; } public function detach(Observer $observer) { if (isset($this->_observers[$observer])) { unset($this->_observers[$observer]); } } public function notify() { foreach ($this->_observers as $observer) { $observer->update(); } } } abstract class Observer { abstract public function update(); } class Concrete_subject extends Subject { private $subject_state; public function __set($param, $value) { if ($param == ‘subject_state‘) { $this->subject_state = $value; } } public function __get($param) { if ($param == ‘subject_state‘) { return $this->subject_state; } } } class Concrete_observer extends Observer { private $name; private $observer_state; private $subject; public function __construct(Concrete_subject $subject, string $name) { $this->subject = $subject; $this->name = $name; } public function update() { $this->observer_state = $this->subject->subject_state; echo "OBSERVER ".$this->name." ‘s STATUS IS".$this->observer_state."<br/>"; } public function __set($param, $value) { if ($param == ‘subject‘) { $this->subject = $value; } } public function __get($param) { if ($param == ‘subject‘) { return $this->subject; } } } //CLIENT CODE $s = new Concrete_subject(); $s->attach(new Concrete_observer($s, ‘X‘)); $s->attach(new Concrete_observer($s, ‘Y‘)); $s->attach(new Concrete_observer($s, ‘Z‘)); $s->subject_state = ‘ABC‘; $s->notify();
观察者模式:
定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态发生变化时,会通知所有观察者对象,使它们能够自动更新自己。
何时使用:
当一个对象的改变需要同时改变其他对象的时候,而且它不知道具体有多少对象有待改变时,应该考虑使用观察者模式;
当一个抽象模型有两个方面,其中一个方面依赖于另一方面,这时用观察者模式可以将这两者封装在独立的对象中使它们各自独立地改变和复用;
总结:
总的来说,观察者模式所做的工作其实就是在解除耦合。让耦合的双方都依赖于抽象,而不是依赖于具体。从而使得各自的变化都不会影响另一边的变化。
另:Observer抽象类 也可以用接口实现。
时间: 2024-11-10 12:59:23