<?php
// 主题接口
interface Subject
{
public function attach(Observer $observer): void;
public function detach(Observer $observer): void;
public function notify(): void;
}
// 具体主题类
class ConcreteSubject implements Subject
{
private $observers = [];
private $state;
public function attach(Observer $observer): void
{
$this->observers[] = $observer;
}
public function detach(Observer $observer): void
{
$this->observers = array_filter($this->observers, function ($o) use ($observer) {
return $o !== $observer;
});
}
public function notify(): void
{
foreach ($this->observers as $observer) {
$observer->update($this);
}
}
public function setState($state): void
{
$this->state = $state;
$this->notify();
}
public function getState()
{
return $this->state;
}
}
// 观察者接口
interface Observer
{
public function update(ConcreteSubject $subject): void;
}
// 具体观察者类
class ConcreteObserver implements Observer
{
private $name;
public function __construct($name)
{
$this->name = $name;
}
public function update(ConcreteSubject $subject): void
{
echo "观察者 {$this->name} 已更新,新的状态是:{$subject->getState()}\n";
}
}
// 客户端代码
$subject = new ConcreteSubject();
$observer1 = new ConcreteObserver("Observer 1");
$observer2 = new ConcreteObserver("Observer 2");
$subject->attach($observer1);
$subject->attach($observer2);
echo "设置状态为 1:\n";
$subject->setState(1);
echo "设置状态为 2:\n";
$subject->setState(2);
$subject->detach($observer1);
echo "设置状态为 3:\n";
$subject->setState(3);