标签:设计模式 观察者模式
<?php /** **observer model :实现一对多的设计,一个对象改变时,依赖于该对象的,都得到通知并且改变。 **可以在独立的对象中维护一个对象,专用于解除主体与依赖者的直接关系 **又称为 发布-监听模式,从属模式,源-监听模式,模式-视图模式 **观察者模式应用:用户注册(验证邮件,用户信息激活) ** ***********/ interface SqlSubject{ function attach(SqlObserver $observer); function detach(SqlObserver $observer); function notify(); } interface SqlObserver{ function update(SqlSubject $subject); } class Subject implements SqlSubject{ private $_object = array(); public function attach(SqlObserver $object){ if(!in_array($object,$this->_object)){ $_object[] = $object; } } public function detach(SqlObserver $observer){ if(false != ($index=array_search($observer,$this->_object))){ unset($this->_object[$index]); } } public function post(){ $this->notify(); } public function notify(){ foreach($this->_object as $val){ $val->update($this); } } public function setCount($count){ echo $count; } public function setIntegeral($integeral){ echo $integeral; } } class Observer1 implements SqlObserver{ public function update(SqlSubject $subject){ $subject->setIntegeral(10); } } class Observer2 implements SqlObserver{ public function update(SqlSubject $subject){ $subject->setCount(20); } } class Client{ public static function main(){ $subject = new Subject(); $subject->attach(new Observer1()); $subject->attach(new Observer2()); $subject->post(); } } Client::main(); ?>
<?php /** **用户注册 *****/ interface SqlSubject{ function attach(); function detach(); function post(); } interface SqlObject{ function update(); } class UserSubject implements SqlSubject{ private $_userEmail = array(); function attach( SqlObject $email,$type){ if(!in_array($email,$type)){ $this->_userEmail[$type][] = $email; } } function detach( SqlObject $email ,$type ){ if(FALSE ! = ($index = array_search($email,$_userEmail))){ unset($_userEmail[$type][$index]); } } function post($type){ $this->notify($this); } function notify($type){ if(!empty($this->_userEmail[$type])) foreach($this->_userEmail($type) as $observer){ $observer->update($this); } } } /** **邮件观察者模式 *********/ class EmailObject implements SqlObject{ function update(SqlSubject $subject){ $this->send($subject->email,$title,$content); } function send($email,$title,$content){ } }
本文出自 “王尼美的成人之路” 博客,请务必保留此出处http://8335914.blog.51cto.com/8325914/1611995
标签:设计模式 观察者模式
原文地址:http://8335914.blog.51cto.com/8325914/1611995