1.观察者模式
PHP内置的类提供了对SPL的原生支持,实现如下。
class ConcreteSubject implements SplSubject
{
private $observers;
private $data;
public function __construct()
{
$this->observers = new SplObjectStorage();
}
public function attach(SplObserver $observer)
{
$this->observers->attach($observer);
}
public function notify()
{
foreach ($this->observers as $observer) {
$observer->update($this);
}
}
public function detach(SplObserver $observer)
{
$this->observers->detach($observer);
}
public function setData($dataNow){
$this->data = $dataNow;
}
public function getData(){
return $this->data;
}
}
class ConcreteObserver implements SplObserver {
public function update(SplSubject $subject)
{
echo $subject->getData();
}
}
class Client
{
public function __construct()
{
echo "create three new concrete observers,a new concrete subject:";
$ob1 = new ConcreteObserver();
$ob2 = new ConcreteObserver();
$ob3 = new ConcreteObserver();
$subject = new ConcreteSubject();
$subject->setObservers();
$subject->setData("here is your data\n");
$subject->attach($ob1);
$subject->attach($ob2);
$subject->attach($ob3);
$subject->notify();
$subject->detach($ob3);
$subject->notify();
}
}
$worker = new Client();
image.png
网友评论