装饰器模式概述与优势
本内容深入解析PHP中的装饰器(Decorator)设计模式,涵盖基础概念及其在实际开发中的应用场景,供开发者参考学习。
若需为现有对象增加新功能,常见做法包括直接修改原类代码、派生子类进行扩展或采用对象组合。其中,直接篡改原类结构通常被视为不良实践。
面向对象设计原则倡导优先使用对象组合来扩展和复用功能,而非依赖继承。装饰器模式正是基于这一理念,通过动态组合机制灵活地为对象附加所需能力,其核心在于以动态手段实现组合目的。
换言之,该模式允许对已有对象的功能或部分逻辑进行调整,而无需改动原始对象的内部结构,从而保持系统的稳定性。
另一种理解方式是保留原有类不变,转而创建专门的装饰器类,通过该类动态注入需要修改或增强的内容。这种方式的显著优势体现在以下方面:
- 首先,它能有效避免类层级因过度继承而变得杂乱无章。
- 其次,当需求变更幅度较小时,无需重构原有的数据结构,降低了维护成本。
接下来结合《PHP设计模式》一书中的经典案例进行具体说明。
/** * 被修饰类 现在的需求: 要求能够动态为CD添加音轨、能显示CD音轨列表。 显示时应采用单行并且为每个音轨都以音轨好为前缀。 */
class CD {
public $trackList;
function __construct() {
# code...
$this->trackList=array();
}
public function addTrack($track){
$this->trackList[]=$track;
}
public function getTrackList(){
$output=" ";
foreach ($this->trackList as $key => $value) {
# code...
$output.=($key+1).") {$value}. ";
}
return $output;
}
}
/* 现在需求发生变化: 要求将当前实例输出的音轨都采用大写形式。 这个需求并不是一个变化特别大的需求,不需要修改基类或创建一个父子关系的子类,此时创建一个基于装饰器模式的装饰器类。 */
class CDTrackListDecoratorCaps{
private $_cd;
public function __construct(CD $CD){
$this->_cd=$CD;
}
public function makeCaps(){
foreach ($this->_cd->trackList as $key => $value) {
# code...
$this->_cd->trackList[$key]=strtoupper($value); //转换成大写
}
}
}
//客户端测试
$myCD=new CD();
$trackList=array( "what It Means", "brr", "goodBye" );
foreach ($trackList as $key => $value) {
# code...
$myCD->addTrack($value);
}
$myCDCaps=new CDTrackListDecoratorCaps($myCD);
$myCDCaps->makeCaps();
print "The CD contains the following tracks:".$myCD->getTrackList();
以一个简单且通俗的场景为例:
- 定义一个UserInfo类,内部包含数组属性用于存储用户名数据。
- 提供addUser方法用于向数组中添加新的用户名记录。
- 通过getUserList方法输出并展示所有已添加的用户名信息。
- 当前需求是将新增的用户名统一转换为大写格式,同时必须确保不改动原有的UserInfo类代码及其数据结构。
- 为此,我们设计了UserInfoDecorate类来实现这一需求,如同装修房屋一般,在不改变主体结构的基础上对外观进行美化。
- 虽然装饰器模式与适配器模式在外观上有些相似,但关键区别在于装饰器模式的核心前提是不改变既有对象的数据结构。
具体实现代码如下:
文件名为UserInfo.php。
//装饰器模式,对已有对象的部分内容或者功能进行调整,但是不需要修改原始对象结构,可以使用装饰器设计模式
class UserInfo {
public $userInfo = array();
public function addUser($userInfo) {
$this->userInfo[] = $userInfo;
}
public function getUserList() {
print_r($this->userInfo);
}
}
//UserInfoDecorate 装饰一样,改变用户信息输出为大写格式,不改变原先UserInfo类
<?php
include("UserInfo.php");
class UserInfoDecorate {
public function makeCaps($UserInfo) {
foreach ($UserInfo->userInfo as &$val) {
$val = strtoupper($val);
}
}
}
$UserInfo = new UserInfo;
$UserInfo->addUser('zhu');
$UserInfo->addUser('initphp');
$UserInfoDecorate = new UserInfoDecorate;
$UserInfoDecorate->makeCaps($UserInfo);
$UserInfo->getUserList();
</code></pre>
<h2>基础案例:用户信息装饰器</h2>至此,我们对装饰器模式有了初步认识。随后将引入一个更复杂的构建案例,源自网络资源,首先查看项目目录结构。
|decorator #项目根目录
|--Think #核心类库
|----Loder.php #自动加载类
|----decorator.php #装饰器接口
|----colorDecorator.php #颜色装饰器
|----sizeDecorator.php #字体大小装饰器
|----echoText.php #被装饰者
|--index.php #单一的入口文件
<h2>进阶案例:多层装饰器构建</h2>首先构建装饰器接口文件 Think/decorator.php,具体内容如下:
<pre class="brush:php;"><code class="language-php">
<?php
/**
* 装饰器接口
* Interface decorator
* @package Think
*/
namespace Think;
interface decorator{
public function beforeDraw();
public function afterDraw();
}
</code></pre>
接着实现颜色装饰器 Think/colorDecorator.php,代码如下:
<pre class="brush:php;"><code class="language-php">
<?php
/**
* 颜色装饰器
*/
namespace Think;
class colorDecorator implements decorator{
protected $color;
public function __construct($color) {
$this->color = $color;
}
public function beforeDraw() {
echo "color decorator :{$this->color}\n";
}
public function afterDraw() {
echo "end color decorator\n";
}
}
</code></pre>
随后是字体大小装饰器 Think/sizeDecorator.php,实现如下:
<pre class="brush:php;"><code class="language-php">
<?php
/**
* 字体大小装饰器
*/
namespace Think;
class sizeDecorator implements decorator{
protected $size;
public function __construct($size) {
$this->size = $size;
}
public function beforeDraw() {
echo "size decorator {$this->size}\n";
}
public function afterDraw() {
echo "end size decorator\n";
}
}
</code></pre>
被装饰者 Think/echoText.php 的定义如下:
<pre class="brush:php;"><code class="language-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();
}
}
}
</code></pre>
自动加载机制 Think/Loder.php 的代码如下:
<pre class="brush:php;"><code class="language-php">
<?php
namespace Think;
class Loder{
static function autoload($class){
require BASEDIR . '/' .str_replace('\\','/',$class) . '.php';
}
}</code></pre>
最后编写入口文件 index.php,代码示例如下:
<pre class="brush:php;"><code class="language-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();
</code></pre>
<h2>Web服务层JSON与XML装饰器</h2>再补充一个Web服务层的案例,即为REST服务提供JSON和XML格式的装饰器,相关代码如下:
文件 RendererInterface.php。
<pre class="brush:php;"><code class="language-php">
<?php
namespace DesignPatterns\Structural\Decorator;
/**
* RendererInterface接口
*/
interface RendererInterface
{
/**
* render data
*
* @return mixed
*/
public function renderData();
}
</code></pre>
文件 Webservice.php。
<pre class="brush:php;"><code class="language-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;
}
}
</code></pre>
文件 Decorator.php。
<pre class="brush:php;"><code class="language-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;
}
}
</code></pre>
文件 RenderInXml.php。
<pre class="brush:php;"><code class="language-php">
<?php
namespace DesignPatterns\Structural\Decorator;
/**
* RenderInXml类
*/
class RenderInXml extends Decorator
{
/**
* render data as XML
*
* @return mixed|string
*/
public function renderData()
{
$output = $this->wrapped->renderData();
// do some fancy conversion to xml from array ...
$doc = new \DOMDocument();
foreach ($output as $key => $val) {
$doc->appendChild($doc->createElement($key, $val));
}
return $doc->saveXML();
}
}
</code></pre>
文件 RenderInJson.php。
<pre class="brush:php;"><code class="language-php">
<?php
namespace DesignPatterns\Structural\Decorator;
/**
* RenderInJson类
*/
class RenderInJson extends Decorator
{
/**
* render data as JSON
*
* @return mixed|string
*/
public function renderData()
{
$output = $this->wrapped->renderData();
return json_encode($output);
}
}</code></pre>
测试文件 Tests/DecoratorTest.php。
<pre class="brush:php;"><code class="language-php">
<?php
namespace DesignPatterns\Structural\Decorator\Tests;
use DesignPatterns\Structural\Decorator;
/**
* DecoratorTest 用于测试装饰器模式
*/
class DecoratorTest extends \PHPUnit_Framework_TestCase
{
protected $service;
protected function setUp()
{
$this->service = new Decorator\Webservice(array('foo' => 'bar'));
}
public function testJsonDecorator()
{
// Wrap service with a JSON decorator for renderers
$service = new Decorator\RenderInJson($this->service);
// Our Renderer will now output JSON instead of an array
$this->assertEquals('{"foo":"bar"}', $service->renderData());
}
public function testXmlDecorator()
{
// Wrap service with a XML decorator for renderers
$service = new Decorator\RenderInXml($this->service);
// Our Renderer will now output XML instead of an array
$xml = '<?xml version="1.0"?>bar';
$this->assertXmlStringEqualsXmlString($xml, $service->renderData());
}
/**
* The first key-point of this pattern :
*/
public function testDecoratorMustImplementsRenderer()
{
$className = 'DesignPatterns\Structural\Decorator\Decorator';
$interfaceName = 'DesignPatterns\Structural\Decorator\RendererInterface';
$this->assertTrue(is_subclass_of($className, $interfaceName));
}
/**
* Second key-point of this pattern : the decorator is type-hinted
*
* @expectedException \PHPUnit_Framework_Error
*/
public function testDecoratorTypeHinted()
{
if (version_compare(PHP_VERSION, '7', '>=')) {
throw new \PHPUnit_Framework_Error('Skip test for PHP 7', 0, __FILE__, __LINE__);
}
$this->getMockForAbstractClass('DesignPatterns\Structural\Decorator\Decorator', array(new \stdClass()));
}
/**
* Second key-point of this pattern : the decorator is type-hinted
*
* @requires PHP 7
* @expectedException TypeError
*/
public function testDecoratorTypeHintedForPhp7()
{
$this->getMockForAbstractClass('DesignPatterns\Structural\Decorator\Decorator', array(new \stdClass()));
}
/**
* The decorator implements and wraps the same interface
*/
public function testDecoratorOnlyAcceptRenderer()
{
$mock = $this->getMock('DesignPatterns\Structural\Decorator\RendererInterface');
$dec = $this->getMockForAbstractClass('DesignPatterns\Structural\Decorator\Decorator', array($mock));
$this->assertNotNull($dec);
}
}
本次关于装饰器模式的记录到此结束。
希望上述内容能对各位的PHP程序设计工作有所帮助。