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