php设计模式(3)-观察者模式
<?php
class User implements SplSubject{
public $loginNum;
public $hobby;
public $observers = null;
public function __construct($hobby){
$this->loginNum = rand(1,10);
$this->hobby = $hobby;
$this->observers = new SplObjectStorage();
}
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();
}
}
public function login(){
$this->notify();
}
}
class Secrity implements SplObserver{
public function update(SplSubject $subject){
echo "第".$subject->loginNum."次登陆";
}
}
class Ad implements SplObserver{
public function update(SplSubject $subject){
echo "爱好".$subject->hobby;
}
}
$user = new User("篮球");
$user->attach(new Secrity());
$user->attach(new Ad());
$user->login();
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。