class user implements SplSubject { public $loginum; public $hobby; protected $observers = null; public function __construct($hobby){ $this->loginum = rand(1,6); $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->loginum < 3){ echo "这是第".$subject->loginum."安全登录"; }else{ echo "这是第".$subject->loginum."登录,异常"; } } } class ad implements SplObserver{ public function update(SplSubject $subject){ if($subject->hobby == 'ad'){ echo "我是".$subject->hobby."nihao"; }else{ echo "这是尼玛"; } } } //实施观察 $user = new user('ad'); $user->attach(new secrity()); $user->attach(new ad()); $user->login();
09-10
09-10