/**
* 发布新闻的主体
*/
class Newspaper implements \SplSubject{
private $name;
private $observers = array();
private $content;
public function __construct($name) {
$this->name = $name;
}
// 添加观察者
public function attach(\SplObserver $observer) {
$this->observers[] = $observer;
}
// 移除观察者
public function detach(\SplObserver $observer) {
$key = array_search($observer,$this->observers, true);
if($key){
unset($this->observers[$key]);
}
}
// 设置突发新闻
public function breakOutNews($content) {
$this->content = $content;
$this->notify();
}
public function getContent() {
return $this->content." (by {$this->name})";
}
// 通知观察者(或部分观察者)
public function notify() {
foreach ($this->observers as $value) {
$value->update($this);
}
}
}
/**
* 接收新闻的观察者
*/
class Reader implements SplObserver{
private $name;
public function __construct($name) {
$this->name = $name;
}
public function update(\SplSubject $subject) {
echo $this->name.' 正在阅读突发新闻 <b>'.$subject->getContent().'</b><br>';
}
}
// 类测试
$newspaper = new Newspaper('纽约时报');
$allen = new Reader('艾伦');
$jim = new Reader('吉姆');
$linda = new Reader('琳达');
// 添加读者
$newspaper->attach($allen);
$newspaper->attach($jim);
$newspaper->attach($linda);
// 移除读者
$newspaper->detach($linda);
// 设置突发新闻
$newspaper->breakOutNews('美国崩溃!');
//=========输出==========
// 艾伦正在阅读突发新闻 美国崩溃! (by 纽约时报)
// 吉姆正在阅读突发新闻 美国崩溃! (by 纽约时报)