观察则设计模式
观察者设计模式简单介绍:
观察者设计模式是属于行为模式
比如:
当以个对象做出改变时,所有依赖他的对象都将得到通知,做出某些改变
/*
被观察者基类
$observers 存储观察者对象
function attach() //追加观察者的方法
function detatch() //取消观察者的方法
function notify() //通知观察者更新的方法
*/
abstract class Subject{
private $observers = [];
//添加观察者方法
public function attach(Observer $observer){
array_push($this->observers,$observer);
}
public function detatch($observer){
foreach ($this->observers as $key => $value) {
if($observer === $value){
unset($this->observers[$key]);
}
}
}
public function notify(){
foreach ($this->observers as $observer) {
$observer->update();
}
}
}
abstract class Observer{
abstract function update();
}
class ConcreateSubject extends Subject{
private $subjectState;
public function setState($state){
$this->subjectState = $state;
}
public function getState(){
return $this->subjectState;
}
}
class ConcreateObserver extends Observer{
private $name;
private $subject;
public function __construct(ConcreateSubject $subject,$name){
$this->subject= $subject;
$this->name = $name;
}
public function update(){
echo '观察者'.$this->name.'的新状态是'.$this->subject->getState().'<br/>';
}
}
$s = new ConcreateSubject();
$s->attach(new ConcreateObserver($s,'X'));//添加一个观察者
$s->attach(new ConcreateObserver($s,'Y'));
$z = new ConcreateObserver($s,'Z');
$s->attach($z);
$s->detatch($z); //删除一个观察者
$s->setState('ABC');
$s->notify();
$s->setState('DEF');
$s->notify();