php观察者模式。
2020-12-13 03:09
标签:style blog class code c http 第一次写博客,大家多多关照!欢迎拍砖哦! 我也刚学设计模式,所以记录下来。 输出 大家自己看吧,项目中我也没用到观察者模式,郁闷! php观察者模式。,搜素材,soscw.com php观察者模式。 标签:style blog class code c http 原文地址:http://www.cnblogs.com/xiaotongs/p/3724525.html
class person{
public
$name;
public
$birthday;
public
function __set($name,$value){
if(isset($this->$name))
$this->$name=$value;
}
public
function __get($name){
if(isset($this->$name))
return
$this->$name;
}
}//观察者类实现SplSubject接口,SplSubject是php内置接口class PersonSubject implements
SplSubject{
public
$observers,$person;
public
function __construct(person $person){
$this->observers = new
SplObjectStorage();
$this->person=$person;
}
//增加一个观察者
public
function attach(SplObserver $observers){
$this->observers->attach($observers);
}
//删除一个观察者
public
function detach(SplObserver $observers){
$this->observers->detach($observers);
}
//达到条件时,通知观察者
public
function notify(){
foreach($this->observers as
$observer){
$observer->update($this);
}
}
//返回被观察者实例,供观察者处理
public
function getPerson(){
return
$this->person;
}
}//观察者实现SplObserver接口,SplObserver是php内置接口class fatherObserver implements
SplObserver{
//条件达到时,执行的动作
public
function update(SplSubject $splsubject){
$person=$splsubject->getPerson();
echo
$person->name.‘ 生日快乐,我是爸爸!‘;
}
}class motherObserver implements
SplObserver{
public
function update(SplSubject $splsubject){
$person=$splsubject->getPerson();
echo
$person->name.‘ 生日快乐,我是妈妈!‘;
}
}class sisterObserver implements
SplObserver{
public
function update(SplSubject $splsubject){
$person=$splsubject->getPerson();
echo
$person->name.‘ 生日快乐,我是姐姐!‘;
}
}//实例化小明$xiaoming=new
person();
$xiaoming->name=‘小明‘;
$xiaoming->birthday=‘0512‘;
//绑定观察者$subject=new
PersonSubject($xiaoming);
$subject->attach(new
fatherObserver);
$subject->attach(new
motherObserver);
$subject->attach(new
sisterObserver);
//如果小明生日到了,通知观察者$date=date(‘md‘,time());
if($xiaoming->birthday==$date){
$subject->notify();
}?>
上一篇:c++容器的底层数据结构