PHP - 设计模式 - 观察者模式

<?php
//观察者模式
//抽象通知者
abstract class Subject {
protected $observer = array() ;
//添加观察者
public abstract function Attach(observer $observer);
//移除观察者
public abstract function Detach(observer $observer);
//通知观察者
punlic abstract function Notify();
}

//具体通知者
class ConcreteSubject extends Subject{
//通知者状态
public $subject_state;
//添加观察者
public function Attach(observer $observer){
array_push($this->subject_state ,$observer);
}
//移除观察者
public function Detach(observer $observer){
foreach ($this->observer as $key => $value) {
if ($val == $observer) {
unset($this->observer[$k])
}
}
}
//通知观察者
public function Notify(observer $observer){
foreach ($this->observer as $key => $value) {
$v->update();
}

}
}

//抽象观察者
abstract class Observer{
public abstract functioin update();
}
//具体观察者
class ConcreteObserver extends Observer{
private $name ;
private $subjectStats ;
//通知者
public $subject ;

public function __construct(ConcreteSubuject $_sub,$_name){
$this->subject = $_sub ;
$this->name = $_name ;
}

public function Update(){
$this->subjectStats = $this->subject->subject_state ;
echo "观察者".$this->name."的新状态是:".$this->subjectStats."<br/>"
}

}

$_s = new ConcreteSubject();
$a = new ConcreteObserver($_s,'a');
$b = new ConcreteObserver($_s,'b');
$c = new ConcreteObserver($_s,'c');

$_s->Attach($a);
$_s->Attach($b);
$_s->Attach($c);

$_s->subject_state = 'xxx';
$_s->Notify();

posted @ 2019-03-30 15:22  千载白云  阅读(127)  评论(0编辑  收藏  举报