码迷,mamicode.com
首页 > 其他好文 > 详细

观察者模式

时间:2016-04-03 23:44:05      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

原文链接:http://www.orlion.ga/719/

解释:

    观察者设计模式能够更便利创建和查看目标对象状态的对象,并且提供和核心对象非耦合的置顶功能性。

代码:

    首先是CD类:

namespace Observer;

class CD{

	public $title;

	public $band;

	protected $_observers = [];

	public function __construct($title , $band) {
		$this->title = $title;
		$this->band = $band;
	}

	public function attachObserver($type ,CDObserver $observer) {
		$this->_observers[$type][] = $observer;
	}

	public function notifyObserver($type) {
		if (isset($this->_observers[$type])) {
			foreach ($this->_observers[$type] as $observer) {
				$observer->update($this);
			}
		}
	}

	public function buy() {
		echo ‘CD buy‘;
		$this->notifyObserver(‘purchased‘);
	}
}

    其中attachObserver()方法注入CD的观察者,而notifyObserver()方法则是通知CD的观察者们,之所以加了一个type是为了更好的对CD的观察者进行分类管理。(也可以理解为不同的事件对应不同的观察者)

    然后就是它的观察者接口CDObserver:

namespace Observer;
interface CDObserver{
	function update(CD $cd);
}

    然后是观察者的实现SendEmailObserver:

namespace Observer;

class SendEmailObserver implements CDObserver{
	public function update(CD $cd) {
		echo $cd->title . "被卖出去了";
	}
}

    在App.php中运行:

require ‘CD.php‘;
require ‘CDObserver.php‘;
require ‘SendEmailObserver.php‘;

$cd = new Observer\CD(‘whats‘ , ‘Simple Plan‘);
$sendEmailObserver = new Observer\SendEmailObserver();
$cd->attachObserver(‘purchased‘ , $sendEmailObserver);
$cd->buy();

   

 

    

观察者模式

标签:

原文地址:http://www.cnblogs.com/orlion/p/5350904.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!