在PHP中,观察者模式可以通过以下步骤来实现:
class Subject {
private $observers = [];
public function registerObserver($observer) {
$this->observers[] = $observer;
}
public function removeObserver($observer) {
$index = array_search($observer, $this->observers);
if ($index !== false) {
unset($this->observers[$index]);
}
}
public function notifyObservers($data) {
foreach ($this->observers as $observer) {
$observer->update($data);
}
}
}
interface Observer {
public function update($data);
}
class ConcreteObserver implements Observer {
public function update($data) {
// 观察者的具体行为,如打印收到的数据
echo "Received data: " . $data;
}
}
$subject = new Subject();
$observer1 = new ConcreteObserver();
$observer2 = new ConcreteObserver();
$subject->registerObserver($observer1);
$subject->registerObserver($observer2);
$data = "Some data";
$subject->notifyObservers($data);
这样,当主题的状态发生变化时,所有注册的观察者都会收到通知,并执行相应的行为。