SplObserver 接口

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

SplObserver 接口与 SplSubject 一起使用以实现观察者设计模式。

接口概要

interface SplObserver {
/* 方法 */
public update(SplSubject $subject): void
}

目录

添加注释

用户贡献注释 2 个注释

aiddroid at example dot com
11 年前
<?php

/**
* 主题,谁发布新闻
*/
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." ({$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.' is reading breakout news <b>'.$subject->getContent().'</b><br>';
}
}

$newspaper = new Newspaper('Newyork Times');

$allen = new Reader('Allen');
$jim = new Reader('Jim');
$linda = new Reader('Linda');

// 添加读者
$newspaper->attach($allen);
$newspaper->attach($jim);
$newspaper->attach($linda);

// 移除读者
$newspaper->detach($linda);

// 设置突发新闻
$newspaper->breakOutNews('USA break down!');

//=====输出======
//Allen is reading breakout news USA break down! (Newyork Times)
//Jim is reading breakout news USA break down! (Newyork Times)
sebastien dot ferrandez at free dot fr
10 年前
注意,你写了

if($key){
unset($this->observers[$key]);
}

而应该写成

if(false !== $key){
unset($this->observers[$key]);
}

如果你要删除的观察者是数组中的第一个,你将永远无法删除它,因为键将等于 0,而 0 == false,正如你所知。
To Top