PHP设计模式之观察者模式浅析(观察者模式应用实例)没想到

随心笔谈1年前 (2023)发布 admin
127 0

<?php
// 主题接口
interface Subject {
public function attach(Observer $observer);
public function detach(Observer $observer);
public function notify();
}
// 观察者接口
interface Observer {
public function update(Subject $subject);
}
// 具体主题类
class ConcreteSubject implements Subject {
private $observers=[];
private $state;
public function attach(Observer $observer) {
$this->observers[]=$observer;
}
public function detach(Observer $observer) {
$index=array_search($observer, $this->observers);
if ($index !==false) {
unset($this->observers[$index]);
}
}
public function notify() {
foreach ($this->observers as $observer) {
$observer->update($this);
}
}
public function getState() {
return $this->state;
}
public function setState($state) {
$this->state=$state;
$this->notify();
}
}
// 具体观察者类
class ConcreteObserver implements Observer {
private $state;
public function update(Subject $subject) {
$this->state=$subject->getState();
}
public function getState() {
return $this->state;
}
}
// 使用观察者模式
$subject=new ConcreteSubject();
$observer1=new ConcreteObserver();
$observer2=new ConcreteObserver();
$subject->attach($observer1);
$subject->attach($observer2);
$subject->setState(“State 1”);
echo $observer1->getState(); // 输出:State 1
echo $observer2->getState(); // 输出:State 1
$subject->setState(“State 2”);
echo $observer1->getState(); // 输出:State 2
echo $observer2->getState(); // 输出:State 2
$subject->detach($observer2);
$subject->setState(“State 3”);
echo $observer1->getState(); // 输出:State 3
echo $observer2->getState(); // 输出:State 2

© 版权声明

相关文章