PHP设计模式之装饰器(装饰者)模式(Decorator)(3)
还有被装饰者 Think/echoText.php,如下:
<?php
/**
* 被装饰者
*/
namespace Think;
class echoText {
protected $decorator = array(); //存放装饰器
//装饰方法
public function index() {
//调用装饰器前置操作
$this->before();
echo "你好,我是装饰器\n";
//执行装饰器后置操作
$this->after();
}
public function addDecorator(Decorator $decorator) {
$this->decorator[] = $decorator;
}
//执行装饰器前置操作 先进先出
public function before() {
foreach ($this->decorator as $decorator){
$decorator->beforeDraw();
}
}
//执行装饰器后置操作 先进后出
public function after() {
$decorators = array_reverse($this->decorator);
foreach ($decorators as $decorator){
$decorator->afterDraw();
}
}
}
再来个自动加载 Think/Loder.php,如下:
<?php
namespace Think;
class Loder{
static function autoload($class){
require BASEDIR . '/' .str_replace('\\','/',$class) . '.php';
}
}
最后就是入口文件index.php了,如下:
<?php
define('BASEDIR',__DIR__);
include BASEDIR . '/Think/Loder.php';
spl_autoload_register('\\Think\\Loder::autoload');
//实例化输出类
$echo = new \Think\echoText();
//增加装饰器
$echo->addDecorator(new \Think\colorDecorator('red'));
//增加装饰器
$echo->addDecorator(new \Think\sizeDecorator('12'));
//装饰方法
$echo->index();
咱最后再来一个案例啊,就是Web服务层 —— 为 REST 服务提供 JSON 和 XML 装饰器,来看代码:
RendererInterface.php
<?php
namespace DesignPatterns\Structural\Decorator;
/**
* RendererInterface接口
*/
interface RendererInterface
{
/**
* render data
*
* @return mixed
*/
public function renderData();
}
Webservice.php
<?php
namespace DesignPatterns\Structural\Decorator;
/**
* Webservice类
*/
class Webservice implements RendererInterface
{
/**
* @var mixed
*/
protected $data;
/**
* @param mixed $data
*/
public function __construct($data)
{
$this->data = $data;
}
/**
* @return string
*/
public function renderData()
{
return $this->data;
}
}
Decorator.php
<?php
namespace DesignPatterns\Structural\Decorator;
/**
* 装饰器必须实现 RendererInterface 接口, 这是装饰器模式的主要特点,
* 否则的话就不是装饰器而只是个包裹类
*/
/**
* Decorator类
*/
abstract class Decorator implements RendererInterface
{
/**
* @var RendererInterface
*/
protected $wrapped;
/**
* 必须类型声明装饰组件以便在子类中可以调用renderData()方法
*
* @param RendererInterface $wrappable
*/
public function __construct(RendererInterface $wrappable)
{
$this->wrapped = $wrappable;
}
}
内容版权声明:除非注明,否则皆为本站原创文章。
