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();//操作session } 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(); ?>