首頁  >  文章  >  後端開發  >  PHP對觀察者模式的原生支援的程式碼詳解

PHP對觀察者模式的原生支援的程式碼詳解

黄舟
黄舟原創
2017-03-15 09:56:471088瀏覽

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