<?php //php设计模式观察者模式 /** 被观察者 */
class user implements SplSubject{ public $lognum; public $hobby; protected $observers=null; public function __construct($hobby){ $this->lognum=rand(1,10); $this->hobby=$hobby; $this->observers=new SplObjectStorage(); } public function login(){ $this->notify(); } public function attach(SplObserver $observer){ $this->observers->attach($observer); } public function detach(SplObserver $observer){ $this->observers->detach($observer); } public function notify(){ $this->observers->rewind(); while($this->observers->valid()){ $observer=$this->observers->current(); $observer->update($this); $this->observers->next(); } } } /** * 观察者 */ class secrity implements SplObserver{ public function update(SplSubject $subject){ if($subject->lognum<3){ echo '这是第'.$subject->lognum.'次安全登录'; }else{ echo '这是第'.$subject->lognum.'次登录,异常'; } } } class ad implements SplObserver{ public function update(SplSubject $subject){ if($subject->hobby=='sports'){ echo '台球英锦赛门票预订'; }else{ echo '好好学习天天向上'; } } } //实施观察 $user=new user('study'); $user->attach(new secrity()); $user->attach(new ad()); $user->login(); ?>
观察者模式属于行为模式,是定义对象间的一种一对多的依赖关系,以便当一个对象的状态发生改变时,所有依 赖于它的对象都得到通知并自动刷新。它完美的将观察者对象和被观察者对象分离。可以在独立的对象(主体)中维护一个对主体感兴趣的依赖项(观察器)列表。 让所有观察器各自实现公共的 Observer 接口,以取消主体和依赖性对象之间的直接依赖关系。
实例Ⅱ
class MySubject implements SplSubject { private $_observers; private $_name; public function __construct($name) { $this->_observers = new SplObjectStorage(); $this->_name = $name; } public function attach(SplObserver $observer) { $this->_observers->attach($observer); } public function detach(SplObserver $observer) { $this->_observers->detach($observer); } public function notify() { foreach ($this->_observers as $observer) { $observer->update($this); } } public function getName() { return $this->_name; } } class MyObserver1 implements SplObserver { public function update(SplSubject $subject) { echo __CLASS__ . ' - ' . $subject->getName(); } } class MyObserver2 implements SplObserver { public function update(SplSubject $subject) { echo __CLASS__ . ' - ' . $subject->getName(); } } $observer1 = new MyObserver1(); $observer2 = new MyObserver2(); $subject = new MySubject("test"); $subject->attach($observer1); $subject->attach($observer2);
$subject->notify();