在 PHP 中实现观察者模式(Observer Pattern)是一种常见的做法,它定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。当主题对象状态发生变化时,它的所有依赖者(观察者)都会自动收到通知并更新。
以下是一个简单的 PHP 示例,展示了如何实现观察者模式:
定义观察者接口 (ObserverInterface.php)
<?php
interface ObserverInterface {
public function update(SubjectInterface $subject);
}
定义主题接口 (SubjectInterface.php)
<?php
interface SubjectInterface {
public function attach(ObserverInterface $observer);
public function detach(ObserverInterface $observer);
public function notify();
}
实现主题 (ConcreteSubject.php)
<?php
include 'SubjectInterface.php';
class ConcreteSubject implements SubjectInterface {
private $observers = [];
private $state;
public function attach(ObserverInterface $observer) {
$this->observers[] = $observer;
}
public function detach(ObserverInterface $observer) {
$key = array_search($observer, $this->observers, true);
if ($key !== false) {
unset($this->observers[$key]);
}
}
public function notify() {
foreach ($this->observers as $observer) {
$observer->update($this);
}
}
public function setState($state) {
$this->state = $state;
$this->notify(); // 状态改变时通知所有观察者
}
public function getState() {
return $this->state;
}
}
实现观察者 (ConcreteObserver.php)
<?php
include 'ObserverInterface.php';
class ConcreteObserver implements ObserverInterface {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function update(SubjectInterface $subject) {
echo $this->name . " received state: " . $subject->getState() . "\n";
}
}
使用
<?php
include 'ConcreteSubject.php';
include 'ConcreteObserver.php';
$subject = new ConcreteSubject();
$observer1 = new ConcreteObserver("Observer 1");
$observer2 = new ConcreteObserver("Observer 2");
$subject->attach($observer1);
$subject->attach($observer2);
$subject->setState("New State"); // 这会触发 notify() 方法,从而更新所有观察者
$subject->detach($observer1); // 移除一个观察者
$subject->setState("Another New State"); // 这将只通知 Observer 2
运行上述代码,你会看到观察者 Observer 1 和 Observer 2 都接收到了第一次状态变化的通知,但由于我们从主题中移除了 Observer 1,所以它不会接收到第二次状态变化的通知。
Was this helpful?
0 / 0