当一个对象的状态发生改变时,依赖它的对象的状态也会随之改变。常用于业务解耦,一个事件发生时,随后通知一系列其他事件更新。
示例
class Observerd {
private $_observer = [];
public function register($observer_name) {
$this->_observer[] = $observer_name;
}
public function trigger() {
foreach($this->_observer as $observer) {
$observer->feedfack();
}
}
}
//观察者要实现的接口
interface Obserable {
public function feedback();
}
class EventsA inplements Obserable {
public function feedback() {
// code...
}
}
class EventsB inplements Obserable {
public function feebback() {
// code...
}
}
//使用
$observerd = new Observerd();
$observerd->register(new EventsA());
$observerd->register(new EventsB());
$observerd->trigger();