标签:
<?php /** * @author v.r And * * @example * 观察者模式 * 观察者设计模式能够更便利的创建查看目标对象状态,并且提供与核心对象非耦合的指定功能 * * 解决问题 * 软件应用回不断要求添加新功能。 如何在不必完全重构某些核心对象的情况下向应用程序添加额外的功能呢? * * (消息通知,插件系统,缓存器构建) * * 电商购买流->购买成功->商品出库->商品货运中 * 活动流构建 * @copyright copyright information * */ class CD { public $band = ‘‘; public $title = ‘‘; protected $observers = array(); public function __construct($title,$band) { $this->title = $title; $this->band = $band; # code... } public function attachObserver($type,$observer) { $this->observers[$type][] = $observer; # code... } public function notifyObserver($type) { if (isset($this->observers[$type])) { foreach ($this->observers[$type] as $observer) { # code... $observer->update($this); } # code... } # code... } public function buy() { # code... # $this->notifyObserver(‘purchased‘); } public function outStorage() { $this->notifyObserver(‘outStorage‘); } } //购买通知流观察者 class buyCDNotifyStreamObserver { public function update(CD $cd) { #可以做逻辑判断做一些信息处理 $activity = "This CD named {$cd->title} by"; $activity .="{$cd->band} was just purchased, "; ActivityStream :: addNewItem($activity); # code... } } //通知流 class ActivityStream { public static function addNewItem($item) { print "\n".$item; # code... } } $title = ‘Waste of a Rib‘; $band = ‘Naver Again‘; $cd = new CD($title,$band); $observer = new buyCDNotifyStreamObserver(); $cd->attachObserver(‘purchased‘,$observer); $cd->buy(); //购买 $cd->attachObserver(‘outStorage‘,$observer); $cd->outStorage(); #end script
标签:
原文地址:http://my.oschina.net/u/1246814/blog/512334