<?php
// 观察者模式
// PHP(SPL)原生支持
/*
类摘要
SplSubject {
abstract public void attach ( SplObserver $observer );
abstract public void detach ( SplObserver $observer );
abstract public void notify ( void );
}
SplObserver {
abstract public void update ( SplSubject $subject );
}
SplObjectStorage implements Countable, Iterator, Serializable, ArrayAccess {
}
*/
class ConcreteSubject implements SplSubject
{
private $storage;
public function __construct() {
$this->storage = new SplObjectStorage();
}
public function attach(SplObserver $obs) {
$this->storage->attach($obs);
}
public function detach(SplObserver $obs) {
$this->storage->detach($obs);
}
public function notify() {
foreach($this->storage as $ol) {
$ol->update($this);
}
}
public function doAct() {
echo 'DoAct ... <br/>';
$this->notify();
}
}
/**
* concrete observer 1
*/
class Observer1 implements SplObserver
{
public function update(SplSubject $sub) {
echo 'Observer one updated! <br/>';
}
}
/**
* concrete observer 2
*/
class Observer2 implements SplObserver
{
public function update(SplSubject $sub) {
echo 'Observer two updated! <br/>';
}
}
// test code
$sub = new ConcreteSubject();
$sub->attach(new Observer1()); //add observer
$sub->attach(new Observer1());
$sub->attach(new Observer2());
$sub->doAct();
PHP对观察者模式的原生支持
最新推荐文章于 2022-10-28 19:45:20 发布