您的位置 首页 php

PHP观察者模式

//观察者模式

class Observer

{

public $observers;

public function setState()

{

$this->notifyAll();

}

private function notifyAll()

{

if(empty($this->observers))return null;

foreach ($this->observers as $key => $value) {

$className = $key;

$funcName = $value;

if (method_exists($className, $funcName))

{

call_user_func(array($className,$funcName));

}

}

}

}

class BinaryObserver extends Observer

{

public $subject;

function __construct($subject)

{

$this->subject = $subject;

$this->subject->observers[‘BinaryObserver’] = ‘update’;

}

protected function update()

{

echo “Binary String: <br />”;

}

}

class OctalObserver extends Observer

{

public $subject;

function __construct($subject)

{

$this->subject = $subject;

$this->subject->observers[‘OctalObserver’] = ‘update’;

//var_dump($this->subject->observers);

}

protected function update()

{

echo “Octal String: <br />”;

}

}

$subject = new Observer();

new BinaryObserver($subject);

new OctalObserver($subject);

$subject->setState();

文章来源:智云一二三科技

文章标题:PHP观察者模式

文章地址:https://www.zhihuclub.com/76518.shtml

关于作者: 智云科技

热门文章

网站地图