本文實(shí)例講述了PHP設(shè)計(jì)模式之裝飾器(裝飾者)模式(Decorator)入門與應(yīng)用。分享給大家供大家參考,具體如下:
通常情況下,我們?nèi)绻o對(duì)象添加功能,要么直接修改對(duì)象添加相應(yīng)的功能,要么派生對(duì)應(yīng)的子類來(lái)擴(kuò)展,抑或是使用對(duì)象組合的方式。顯然,直接修改對(duì)應(yīng)的類這種方式并不可取。
在面向?qū)ο蟮脑O(shè)計(jì)中,我們也應(yīng)該盡量使用對(duì)象組合,而不是對(duì)象繼承來(lái)擴(kuò)展和復(fù)用功能。裝飾器模式就是基于對(duì)象組合的方式,可以很靈活的給對(duì)象添加所需要的功能,并且它的本質(zhì)就是動(dòng)態(tài)組合,一句話,動(dòng)態(tài)是手段,組合才是目的。
也就是說(shuō),在這種模式下,我們可以對(duì)已有對(duì)象的部分內(nèi)容或者功能進(jìn)行調(diào)整,但是不需要修改原始對(duì)象結(jié)構(gòu),理解了不???
還可以理解為,我們不去修改已有的類,而是通過(guò)創(chuàng)建另外一個(gè)裝飾器類,通過(guò)這個(gè)裝飾器類去動(dòng)態(tài)的擴(kuò)展其需要修改的內(nèi)容。而它的好處也是顯而易見的,如下:
我們來(lái)看下《PHP設(shè)計(jì)模式》里面的一個(gè)案例:
/** * 被修飾類 現(xiàn)在的需求: 要求能夠動(dòng)態(tài)為CD添加音軌、能顯示CD音軌列表。 顯示時(shí)應(yīng)采用單行并且為每個(gè)音軌都以音軌好為前綴。 */ 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ā)生變化: 要求將當(dāng)前實(shí)例輸出的音軌都采用大寫形式。 這個(gè)需求并不是一個(gè)變化特別大的需求,不需要修改基類或創(chuàng)建一個(gè)父子關(guān)系的子類,此時(shí)創(chuàng)建一個(gè)基于裝飾器模式的裝飾器類。 */ 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); //轉(zhuǎn)換成大寫 } } } //客戶端測(cè)試 $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();
來(lái)看一個(gè)比較通俗但是比較簡(jiǎn)單的案例:
代碼如下:
UserInfo.php
//裝飾器模式,對(duì)已有對(duì)象的部分內(nèi)容或者功能進(jìn)行調(diào)整,但是不需要修改原始對(duì)象結(jié)構(gòu),可以使用裝飾器設(shè)計(jì)模式 class UserInfo { public $userInfo = array(); public function addUser($userInfo) { $this->userInfo[] = $userInfo; } public function getUserList() { print_r($this->userInfo); } }
//UserInfoDecorate 裝飾一樣,改變用戶信息輸出為大寫格式,不改變?cè)萓serInfo類 ?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();
到此,咱們應(yīng)該是對(duì)于裝飾器模式有了一個(gè)大概的了解,接下來(lái)咱們看一下構(gòu)建裝飾器模式的案例,網(wǎng)上的,先來(lái)看目錄結(jié)構(gòu):
|decorator #項(xiàng)目根目錄
|--Think #核心類庫(kù)
|----Loder.php #自動(dòng)加載類
|----decorator.php #裝飾器接口
|----colorDecorator.php #顏色裝飾器
|----sizeDecorator.php #字體大小裝飾器
|----echoText.php #被裝飾者
|--index.php #單一的入口文件
完事就是來(lái)構(gòu)建裝飾器接口,Think/decorator.php,如下:
?php /** * 裝飾器接口 * Interface decorator * @package Think */ namespace Think; interface decorator{ public function beforeDraw(); public function afterDraw(); }
再來(lái)就是顏色裝飾器 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() { //調(diào)用裝飾器前置操作 $this->before(); echo "你好,我是裝飾器\n"; //執(zhí)行裝飾器后置操作 $this->after(); } public function addDecorator(Decorator $decorator) { $this->decorator[] = $decorator; } //執(zhí)行裝飾器前置操作 先進(jìn)先出 public function before() { foreach ($this->decorator as $decorator){ $decorator->beforeDraw(); } } //執(zhí)行裝飾器后置操作 先進(jìn)后出 public function after() { $decorators = array_reverse($this->decorator); foreach ($decorators as $decorator){ $decorator->afterDraw(); } } }
再來(lái)個(gè)自動(dòng)加載 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'); //實(shí)例化輸出類 $echo = new \Think\echoText(); //增加裝飾器 $echo->addDecorator(new \Think\colorDecorator('red')); //增加裝飾器 $echo->addDecorator(new \Think\sizeDecorator('12')); //裝飾方法 $echo->index();
咱最后再來(lái)一個(gè)案例啊,就是Web服務(wù)層 —— 為 REST 服務(wù)提供 JSON 和 XML 裝飾器,來(lái)看代碼:
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; /** * 裝飾器必須實(shí)現(xiàn) RendererInterface 接口, 這是裝飾器模式的主要特點(diǎn), * 否則的話就不是裝飾器而只是個(gè)包裹類 */ /** * Decorator類 */ abstract class Decorator implements RendererInterface { /** * @var RendererInterface */ protected $wrapped; /** * 必須類型聲明裝飾組件以便在子類中可以調(diào)用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 用于測(cè)試裝飾器模式 */ 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); } }
好啦,本次記錄就到這里了。
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語(yǔ)法入門教程》、《PHP運(yùn)算與運(yùn)算符用法總結(jié)》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫(kù)操作入門教程》及《php常見數(shù)據(jù)庫(kù)操作技巧匯總》
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。
標(biāo)簽:南陽(yáng) 婁底 寶雞 湛江 宜賓 鎮(zhèn)江 銅川 黃南
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《PHP設(shè)計(jì)模式之裝飾器(裝飾者)模式(Decorator)入門與應(yīng)用詳解》,本文關(guān)鍵詞 PHP,設(shè)計(jì)模式,之,裝飾,器,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。