观察者模式:定义了对象间的一种一对多的依赖关系,当被观察的对象发生改变时,所有依赖于它的对象都会得到通知并被自动更新,而且被观察的对象和观察者之间是松耦合的。在该模式中,有目标(Subject)和观察者(Observer)两种角色。目标角色是被观察的对象,持有并控制着某种状态,可以被任意多个观察者作为观察的目标。也叫发布--订阅模式
简单实例:再PC端登录帐号时,其他客户端帐号被踢下线,实现同一时间只能在一处登录帐号。
//目标,被观察 class user implements SplSubject { public $username=''; public $password=''; public $observers=null; public function __construct($username,$password){ $this->username=$username; $this->password=$password; $this->observers=new SplObjectStorage(); } public function attach(SplObserver $observer) { // TODO: Implement attach() method. $this->observers->attach($observer); } public function detach(SplObserver $observer) { // TODO: Implement attach() method. $this->observers->detach($observer); } public function notify() { // TODO: Implement notify() method. $userinfo['username']=$this->username; foreach ($this->observers as $observer) { $observer->update($this, $userinfo); } } public function login(){ echo 'PC: '.$this->username.' login in'; //通知 $this->notify(); } } class ios implements SplObserver{ public function update(SplSubject $subject) { // TODO: Implement update() method. if (func_num_args() === 2) { $userinfo = func_get_arg(1); echo "<br>"; echo 'IOS: ' . $userinfo['username'] . ' login out '; } } } class android implements SplObserver{ public function update(SplSubject $subject) { // TODO: Implement update() method. if (func_num_args() === 2) { $userinfo = func_get_arg(1); echo "<br>"; echo 'android: ' . $userinfo['username'] . ' login out '; } } } $user=new user('tom','123456'); //添加观察者 $user->attach(new ios()); $user->attach(new android()); //通知 $user->login();
详细请参考:
https://www.ibm.com/developerworks/cn/opensource/os-cn-observerspl/