当对象间存在一对多关系时,则使用观察者模式(Observer Pattern)。比如,当一个对象被修改时,则会自动通知它的依赖对象。观察者模式属于行为型模式。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
|
class user implements SplSubject {
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 $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(); }
}
class security 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('sports'); $user->attach(new security()); $user->attach(new ad());
$user->login();
|