PHP设计模式之装饰器(装饰者)模式(Decorator)入门与应用详解


Posted in PHP onDecember 13, 2019

本文实例讲述了PHP设计模式之装饰器(装饰者)模式(Decorator)入门与应用。分享给大家供大家参考,具体如下:

通常情况下,我们如果要给对象添加功能,要么直接修改对象添加相应的功能,要么派生对应的子类来扩展,抑或是使用对象组合的方式。显然,直接修改对应的类这种方式并不可取。

在面向对象的设计中,我们也应该尽量使用对象组合,而不是对象继承来扩展和复用功能。装饰器模式就是基于对象组合的方式,可以很灵活的给对象添加所需要的功能,并且它的本质就是动态组合,一句话,动态是手段,组合才是目的。

也就是说,在这种模式下,我们可以对已有对象的部分内容或者功能进行调整,但是不需要修改原始对象结构,理解了不???

还可以理解为,我们不去修改已有的类,而是通过创建另外一个装饰器类,通过这个装饰器类去动态的扩展其需要修改的内容。而它的好处也是显而易见的,如下:

  • 1、我们可以保证类的层次不会因过多而发生混乱。
  • 2、当我们需求的修改很小时,不用改变原有的数据结构。

我们来看下《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类,里面有UserInfo数组,用于存储用户名信息
  • 通过addUser来添加用户名
  • getUserList方法将打印出用户名信息
  • 现在需要将添加的用户信息变成大写的,我们需要不改变原先的类,并且不改变原先的数据结构
  • 我们设计了一个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();

到此,咱们应该是对于装饰器模式有了一个大概的了解,接下来咱们看一下构建装饰器模式的案例,网上的,先来看目录结构:

|decorator  #项目根目录
|--Think  #核心类库
|----Loder.php  #自动加载类
|----decorator.php  #装饰器接口
|----colorDecorator.php  #颜色装饰器
|----sizeDecorator.php  #字体大小装饰器
|----echoText.php  #被装饰者
|--index.php #单一的入口文件

完事就是来构建装饰器接口,Think/decorator.php,如下:

<?php
/**
 * 装饰器接口
 * Interface decorator
 * @package Think
 */
namespace Think;
interface decorator{
  public function beforeDraw();
  public function afterDraw();
}

再来就是颜色装饰器 Think/colorDecorator.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";
  }
}

还有就是字体大小装饰器 Think/sizeDecorator.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";
  }
}

还有被装饰者 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;
  }
}

RenderInXml.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();
  }
}

RenderInJson.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);
  }
}

Tests/DecoratorTest.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"?><foo>bar</foo>';
    $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程序设计有所帮助。

PHP 相关文章推荐
php 保留小数点
Apr 21 PHP
常见的PHP五种设计模式小结
Mar 23 PHP
php cli模式学习(PHP命令行模式)
Jun 03 PHP
免费的ip数据库淘宝IP地址库简介和PHP调用实例
Apr 08 PHP
基于php判断客户端类型
Oct 14 PHP
PHP环境搭建(php+Apache+mysql)
Nov 14 PHP
phpinfo()中Loaded Configuration File(none)的解决方法
Jan 16 PHP
PHP使用第三方即时获取物流动态实例详解
Apr 27 PHP
PHP实现批量清空删除指定文件夹所有内容的方法
May 30 PHP
laravel-admin select框默认选中的方法
Oct 03 PHP
Laravel基础_关于view共享数据的示例讲解
Oct 14 PHP
laravel通用化的CURD的实现
Dec 13 #PHP
Vagrant(WSL)+PHPStorm+Xdebu 断点调试环境搭建
Dec 13 #PHP
phpstudy后门rce批量利用脚本的实现
Dec 12 #PHP
PHP设计模式之数据访问对象模式(DAO)原理与用法实例分析
Dec 12 #PHP
PHP设计模式之建造者模式(Builder)原理与用法案例详解
Dec 12 #PHP
PHP设计模式之适配器模式(Adapter)原理与用法详解
Dec 12 #PHP
PHP学习记录之常用的魔术常量详解
Dec 12 #PHP
You might like
PHP写的求多项式导数的函数代码
2012/07/04 PHP
PHP错误提示的关闭方法详解
2013/06/23 PHP
PHP屏蔽过滤指定关键字的方法
2014/11/03 PHP
php中session定期自动清理的方法
2015/11/12 PHP
功能强大的php文件上传类
2016/08/29 PHP
PHP入门教程之上传文件实例详解
2016/09/11 PHP
PHP PDOStatement::getColumnMeta讲解
2019/02/01 PHP
深入理解Javascript闭包 新手版
2010/12/28 Javascript
Js 时间函数getYear()的使用问题探讨
2013/04/01 Javascript
关于jquery input textare 事件绑定及用法学习
2013/04/03 Javascript
jQuery遍历Table应用示例
2014/04/09 Javascript
如何解决ligerUI布局时Center中的Tab高度大小
2015/11/24 Javascript
Three.js学习之网格
2016/08/10 Javascript
jquery移除了live()、die(),新版事件绑定on()、off()的方法
2016/10/26 Javascript
令按钮悬浮在(手机)页面底部的实现方法
2017/05/02 Javascript
jQuery实现手势解锁密码特效
2017/08/14 jQuery
vue项目中v-model父子组件通信的实现详解
2017/12/10 Javascript
深入理解Vue Computed计算属性原理
2018/05/29 Javascript
微信小程序中显示倒计时代码实例
2019/05/09 Javascript
NodeJs实现简易WEB上传下载服务器
2019/08/10 NodeJs
微信小程序如何实现点击图片放大功能
2020/01/21 Javascript
JavaScript 链表定义与使用方法示例
2020/04/28 Javascript
使用python实现strcmp函数功能示例
2014/03/25 Python
在Django框架中运行Python应用全攻略
2015/07/17 Python
python读取LMDB中图像的方法
2018/07/02 Python
python实现诗歌游戏(类继承)
2019/02/26 Python
python实现京东订单推送到测试环境,提供便利操作示例
2019/08/09 Python
python SVD压缩图像的实现代码
2019/11/05 Python
python+selenium定时爬取丁香园的新型冠状病毒数据并制作出类似的地图(部署到云服务器)
2020/02/09 Python
Windows 下更改 jupyterlab 默认启动位置的教程详解
2020/05/18 Python
详解如何在css中引入自定义字体(font-face)
2018/05/17 HTML / CSS
2014党员学习兰辉先进事迹思想汇报
2014/09/17 职场文书
酒店管理专业毕业生自我鉴定
2014/09/29 职场文书
html css3不拉伸图片显示效果
2021/06/07 HTML / CSS
Linux系统下MySQL配置主从分离的步骤
2022/03/21 MySQL
MySQL控制流函数(-if ,elseif,else,case...when)
2022/07/07 MySQL