首页 >后端开发 >php教程 >PHP对观察者模式的原生支持的代码详解

PHP对观察者模式的原生支持的代码详解

黄舟
黄舟原创
2017-03-15 09:56:471112浏览

PHP对观察者模式的原生支持的代码详解

<?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 &#39;DoAct ... <br/>&#39;;
		$this->notify();
	}
}

/**
 * concrete observer 1
 */
class Observer1 implements SplObserver
{
	public function update(SplSubject $sub) {
		echo &#39;Observer one updated! <br/>&#39;;
	}
}

/**
 * concrete observer 2
 */
class Observer2 implements SplObserver
{
	public function update(SplSubject $sub) {
		echo &#39;Observer two updated! <br/>&#39;;
	}
}

// test code
$sub = new ConcreteSubject();

$sub->attach(new Observer1()); //add observer
$sub->attach(new Observer1());
$sub->attach(new Observer2());

$sub->doAct();

以上是PHP对观察者模式的原生支持的代码详解的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn