本文實例講述了PHP設計模式之裝飾器(裝飾者)模式(Decorator)入門與應用。分享給大家供大家參考,具體如下:
通常情況下,我們如果要給對象添加功能,要么直接修改對象添加相應的功能,要么派生對應的子類來擴展,抑或是使用對象組合的方式。顯然,直接修改對應的類這種方式并不可取。
在面向對象的設計中,我們也應該盡量使用對象組合,而不是對象繼承來擴展和復用功能。裝飾器模式就是基于對象組合的方式,可以很靈活的給對象添加所需要的功能,并且它的本質就是動態(tài)組合,一句話,動態(tài)是手段,組合才是目的。
也就是說,在這種模式下,我們可以對已有對象的部分內容或者功能進行調整,但是不需要修改原始對象結構,理解了不???
還可以理解為,我們不去修改已有的類,而是通過創(chuàng)建另外一個裝飾器類,通過這個裝飾器類去動態(tài)的擴展其需要修改的內容。而它的好處也是顯而易見的,如下:
- 1、我們可以保證類的層次不會因過多而發(fā)生混亂。
- 2、當我們需求的修改很小時,不用改變原有的數(shù)據(jù)結構。
我們來看下《PHP設計模式》里面的一個案例:
/** * 被修飾類 現(xiàn)在的需求: 要求能夠動態(tài)為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;
}
}
/* 現(xiàn)在需求發(fā)生變化: 要求將當前實例輸出的音軌都采用大寫形式。 這個需求并不是一個變化特別大的需求,不需要修改基類或創(chuàng)建一個父子關系的子類,此時創(chuàng)建一個基于裝飾器模式的裝飾器類。 */
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數(shù)組,用于存儲用戶名信息
- 通過addUser來添加用戶名
- getUserList方法將打印出用戶名信息
- 現(xiàn)在需要將添加的用戶信息變成大寫的,我們需要不改變原先的類,并且不改變原先的數(shù)據(jù)結構
- 我們設計了一個UserInfoDecorate類來完成這個需求的操作,就像裝飾一樣,給原先的數(shù)據(jù)進行了裝修
- 裝飾器模式有些像適配器模式,但是一定要注意,裝飾器主要是不改變現(xiàn)有對象數(shù)據(jù)結構的前提
代碼如下:
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();
到此,咱們應該是對于裝飾器模式有了一個大概的了解,接下來咱們看一下構建裝飾器模式的案例,網(wǎng)上的,先來看目錄結構:
|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";
//執(zhí)行裝飾器后置操作
$this->after();
}
public function addDecorator(Decorator $decorator) {
$this->decorator[] = $decorator;
}
//執(zhí)行裝飾器前置操作 先進先出
public function before() {
foreach ($this->decorator as $decorator){
$decorator->beforeDraw();
}
}
//執(zhí)行裝飾器后置操作 先進后出
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;
/**
* 裝飾器必須實現(xiàn) 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數(shù)組(Array)操作技巧大全》、《PHP基本語法入門教程》、《PHP運算與運算符用法總結》、《php字符串(string)用法總結》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。
您可能感興趣的文章:- php設計模式 Facade(外觀模式)
- 詳解PHP中的外觀模式facade pattern
- 學習php設計模式 php實現(xiàn)門面模式(Facade)
- PHP設計模式之數(shù)據(jù)訪問對象模式(DAO)原理與用法實例分析
- PHP設計模式之建造者模式(Builder)原理與用法案例詳解
- PHP設計模式之適配器模式(Adapter)原理與用法詳解
- PHP設計模式之策略模式(Strategy)入門與應用案例詳解
- PHP經(jīng)典面試題之設計模式(經(jīng)常遇到)
- php設計模式小結
- PHP設計模式之外觀模式(Facade)入門與應用詳解