1 <?php 2 /** 3 * 观察者模式(被观察者) 4 * 5 * @author Administrator 6 * 7 */ 8 class Subject implements SplSubject { 9 10 /** 11 * 设置的参数 12 * 13 * @var mixed 14 */ 15 protected $_value; 16 17 /** 18 * 19 * 20 * @var SplObjectStorage 21 */ 22 protected $_observers; 23 24 /** 25 * 构造函数 26 * 27 * @return void 28 */ 29 public function __construct() { 30 $this->_observers = new SplObjectStorage(); 31 } 32 33 /** 34 * (non-PHPdoc) 35 * @see SplSubject::attach() 36 */ 37 public function attach(SplObserver $observer) { 38 $this->_observers->attach($observer); 39 } 40 41 /** 42 * (non-PHPdoc) 43 * @see SplSubject::detach() 44 */ 45 public function detach(SplObserver $observer) { 46 $this->_observers->detach($observer); 47 } 48 49 /** 50 * (non-PHPdoc) 51 * @see SplSubject::notify() 52 */ 53 public function notify() { 54 foreach ($this->_observers as $observer) { 55 $observer->update($this); 56 } 57 } 58 59 /** 60 * 设置最新值 61 * 62 * @param mixed $value 63 * @return 64 */ 65 public function setValue($value) { 66 $this->_value = $value; 67 $this->notify(); 68 } 69 70 /** 71 * 获取最后更新的值 72 * 73 * @return mixed 74 */ 75 public function getValue() { 76 return $this->_value; 77 } 78 } 79 80 /** 81 * 观察者模式(观察者) 82 * 83 * @author Administrator 84 * 85 */ 86 class Observer implements SplObserver { 87 88 /** 89 * (non-PHPdoc) 90 * @see SplObserver::update() 91 */ 92 public function update(SplSubject $subject) { 93 var_dump('最后更新时间为:' . $subject->getValue()); 94 } 95 } 96 97 date_default_timezone_set('Asia/Shanghai'); 98 error_reporting(E_ALL); 99 $subject = new Subject(); 100 $observer = new Observer(); 101 $subject->attach($observer); 102 $subject->setValue(date('Y-m-d H:i:s', time()));
|
请发表评论