定义了一种一对多的依赖关系,多个观察者对象同时监听某一主题的变化,这个主题对象在状态发生变化时,会通知所有观察者对象,使它们可以更新自己.
应用场景:
某个实例的变化影响到了其他对象.
UML:
示例代码:
class Product { private $observers = array(); private $pid = 0; public function __construct($pid) { $this->pid = $pid; } // 注册观察者 public function attachObserver($observer) { $this->observers[] = $observer; } public function buy() { //..... $this->notify(); } // 通知观察者 public function notify() { foreach ($this->observers as $obj) { $obj->receiveBuy($this); } } public function getPid() { return $this->pid; } } interface ProductObserver { public function receiveBuy(Product $pro); } class Repertory implements ProductObserver { public function receiveBuy(Product $pro) { echo $pro->getPid() . "被购买了,库存可以减去1了"; } } // 调用示例 $product = new Product('s100'); $product->attachObserver(new Repertory()); $product->buy(); // 产品一旦被购买,我们就通知库存.