在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);
這樣,當主題的狀態發生變化時,所有注冊的觀察者都會收到通知,并執行相應的行為。