PHP 代码:PHP 观察者模式
以下代码是基于在 PHP 中观察者模式的实现。以供大家下
//被察者抽象类
class
Observed
implements
SplSubject{
protected
$_name
;
protected
$_observers
;
//实例化,生成一个观察者对象
public
function
__construct(){
$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(){
foreach
(
$this
->_observers
as
$observer
){
$observer
->showMessage(
$this
);
}
}
//普通方法: 设置值
public
function
setName(
$name
){
$this
->_name =
$name
;
$this
->notify();
}
//普通方法: 获取值
public
function
getName(){
return
$this
->_name;
}
//普通方法:设置年龄
public
function
setAge(
$age
){
$this
->age =
$age
;
foreach
(
$this
->_observers
as
$observer
){
$observer
->showAge(
$this
->_name,
$this
->age);