首頁 > php教程 > php手册 > 主體

简单的订阅者模式

WBOY
發布: 2016-06-06 19:37:45
原創
1356 人瀏覽過

Lynda 假设有一个系统服务,有几个模块需要使用服务,组件可以订阅这个服务或消息,通过系统广播通知所有的模块。 无 ?php// 订阅发布模式 接口的定义及消息的传递class Dispatcher{ // 监视public static $listeners = array();protected function __constru

Lynda
假设有一个系统服务,有几个模块需要使用服务,组件可以订阅这个服务或消息,通过系统广播通知所有的模块。
<?php
// 订阅发布模式 接口的定义及消息的传递

class Dispatcher
{
        // 监视
	public static $listeners = array();
	protected function __construct(){}
	
	// 订阅服务
	public static function subscribe($object, $subscribe)
	{
		$id = spl_object_hash($object);
		self::$listeners[$id][] = $subscribe;
	}
	// 广播消息
	public static function publish($object)
	{
		$id = spl_object_hash($object);			
		foreach (self::$listeners[$id] as $subscriber) {			
			//var_dump($subscriber);
			$subscriber->doSomething();
		}
	}
}

class Service
{
	protected $name = '';
	public function __construct($name)
	{
		$this->name = $name;
	}
        // 触发动作
	public function doSomething()
	{		
		echo sprintf("%s has something happened.\n", $this->name);		
		Dispatcher::publish($this);				
	}
}

class Component
{
	protected $name = '';
	public function __construct($name)
	{
		$this->name = $name;
	}

	public function doSomething()
	{		
		echo sprintf("%s did something.\n", $this->name);				
	}
}

$serviceA  = new Service("ServiceA");
$componentA = new Component("componentA");
$componentB = new Component("componentB");
$componentC = new Component("componentC");

Dispatcher::subscribe($serviceA, $componentA);
Dispatcher::subscribe($serviceA, $componentB);
Dispatcher::subscribe($serviceA, $componentC);
// 触发一个动作
$serviceA->doSomething();
// output
//ServiceA something happened.
//componentA did something.
//componentB did something.
//componentC did something.
登入後複製
相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門推薦
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!