码迷,mamicode.com
首页 > Web开发 > 详细

php设计模式(3)-观察者模式

时间:2015-01-11 20:21:41      阅读:283      评论:0      收藏:0      [点我收藏+]

标签:

<?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();

php设计模式(3)-观察者模式

标签:

原文地址:http://www.cnblogs.com/shenming/p/4217002.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!