观察者模式用于监听关联类的行为,如果有所异常并作出回应;
<?php //观察者模式:一个类的行为(方法)被另外一个类的行为(方法)所观察甚至限制 //男人类:大丈夫有两个行为,加入女朋友监察和自行购物行为 class Man{ private $observer=array(); //加入观察者对象 public function addObserver($observer) { $this->observer[] = $observer; } public function buy() { foreach($this->observer as $observer){ //在男人购买方法中加入女朋友对象来观察监听男人的消费 $observer->dongjie(); } } //移除观察者 public function delObserver($observer) { $key = array_search($observer,$this->observer); array_splice($this->observer,$key,1); } } //女朋友类有个自发行为:冻结男朋友的消费卡的行为 class GirlFriend{ private $name; function __construct($name) { $this->name = $name; } public function dongjie() { echo $this->name."说道想偷偷花钱买东西,没门!<br />"; } } $xiaoli = new GirlFriend('小丽'); //var_dump($xiaoli);die(); $xiaohua = new GirlFriend('小花'); $xiaoming = new Man(); $xiaoming->addObserver($xiaoli); $xiaoming->addObserver($xiaohua); $xiaoming->delObserver($xiaohua); $xiaoming->buy();code.php