当前位置:Gxlcms > PHP教程 > PHP观察者模式的代码实例

PHP观察者模式的代码实例

时间:2021-07-01 10:21:17 帮助过:13人阅读

PHP观察者模式的代码实例

<?php
// 观察者模式

/**
 * abstract subject
 */
interface Subject
{
	/**
	 * add Observer
	 */
	public function attach(Observer $obs);
	
	/**
	 * remove Observer
	 */
	public function detach(Observer $obs);
	
	/**
	 * notify Observer
	 */
	public function notify();
}

interface Observer
{
	public function update(Subject $sub);
}

/**
 * concrete subject
 */
class ConcreteSubject implements Subject
{
	private $observerList = array();
	
	public function attach(Observer $obs) {
		$this->observerList[] = $obs;
	}
	
	public function detach(Observer $obs) {
		$this->observerList = array_diff($this->observerList, [$obs]);
	}
	
	public function notify() {
		foreach($this->observerList as $ol) {
			$ol->update($this);
		}
	}
	
	public function doAct() {
		echo 'DoAct ... <br/>';
		$this->notify();
	}
}

/**
 * concrete observer 1
 */
class Observer1 implements Observer
{
	public function update(Subject $sub) {
		echo 'Observer one updated! <br/>';
	}
}

/**
 * concrete observer 2
 */
class Observer2 implements Observer
{
	public function update(Subject $sub) {
		echo 'Observer two updated! <br/>';
	}
}

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

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

$sub->doAct();

以上就是PHP观察者模式的代码实例的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行