<?php
//观察者设计模式能够更便利地创建查看目标对象状态的对象,并且提供与核心对象非耦合的指定功能性。
class CD{
public $title = '';
public $band = '';
protected $_observers = [];
public function __construct($title, $band){
$this->title = $title;
$this->band = $band;
}
public function attachObserver($type, $observer){
$this->_observers[$type][] = $observer;
}
public function notifyObserver($type){
if(isset($this->_observers[$type])){
foreach($this->_observers[$type] as $observer){
$observer->update($this);
}
}
}
public function buy(){
$this->notifyObserver('purchased');
}
}
class buyCDNotifyStreamObserver{
public function update($cd){
$activity = "The CD named {$cd->title} by ";
$activity .= "{$cd->band} was just purchased. ";
activityStream::addNewItem($activity);
}
}
class activityStream{
public static function addNewItem($item){
echo $item;
}
}
$title = 'Waste of a Rib';
$band = 'Never Again';
$cd = new CD($title, $band);
$observer = new buyCDNotifyStreamObserver();
$cd->attachObserver('purchased', $observer);
$cd->buy();
//在创建其核心功能性可能包含可观察者状态变化的对象时,最佳的做法是基于观察者设计模式创建与目标对象进行交互的其他类。