前言
观察者模式属于行为模式,是定义对象间的一种一对多的依赖关系,以便当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并自动刷新。
代码
<?php
//抽象一个观察者
abstract class Observed
{
abstract function update();
}
//被观察者抽象类
abstract class Observer
{
private $observeds = []; //被挂载的观察者们
//加入一个观察者
public function attach($observed)
{
array_push($this->observeds, $observed);
}
//移除一个观察者
public function remove($observed)
{
foreach ($this->observeds as &$value) {
if ($value === $observed) {
unset($value);
}
}
}
//通知所有观察者
public function notify()
{
foreach ($this->observeds as &$observed) {
$observed->update();
}
}
}
//创建一个同学类观察目标
class Menber extends Observed
{
public $name = '';
public $target;
public $func;
public function __construct($name, $target, $func)
{
$this->name = $name;
$this->target = $target;
$this->func = $func;
}
public function update()
{
echo $this->name . '观察到目标【' . $this->target->name . '】说:' . $this->target->language . PHP_EOL;
echo '于是' . call_user_func($this->func);
}
}
//创建一个目标类(被观察的)
class Target extends Observer
{
public $name;
public $language;
public function __construct($name)
{
$this->name = $name;
}
public function say($language)
{
$this->language = $language;
echo $this->name . '说:' . $language . PHP_EOL;
}
}
$target = new Target('蔡旭困');
$target->attach(new Menber('粉丝', $target, function () {
return '大喊:坤坤你好棒!' . PHP_EOL;
}));
$target->attach(new Menber('黑粉', $target, function () {
return '嘲讽:律师含!律师含!!' . PHP_EOL;
}));
$target->attach(new Menber('吃瓜群众', $target, function () {
return '说:鲲之大,一锅炖不下!' . PHP_EOL;
}));
$target->attach(new Menber('狗仔队', $target, function () {
return '说:明天的头条就是你了!' . PHP_EOL;
}));
$target->say('全民制作人们大家好,我是练习时长两年半的个人练习生,喜欢唱、跳、rap!');
$target->notify();
网友评论