本文實(shí)例講述了PHP設(shè)計(jì)模式之裝飾器(裝飾者)模式(Decorator)入門與應(yīng)用。分享給大家供大家參考,具體如下:
通常情況下,我們?nèi)绻o對象添加功能,要么直接修改對象添加相應(yīng)的功能,要么派生對應(yīng)的子類來擴(kuò)展,抑或是使用對象組合的方式。顯然,直接修改對應(yīng)的類這種方式并不可取。
在面向?qū)ο蟮脑O(shè)計(jì)中,我們也應(yīng)該盡量使用對象組合,而不是對象繼承來擴(kuò)展和復(fù)用功能。裝飾器模式就是基于對象組合的方式,可以很靈活的給對象添加所需要的功能,并且它的本質(zhì)就是動態(tài)組合,一句話,動態(tài)是手段,組合才是目的。
也就是說,在這種模式下,我們可以對已有對象的部分內(nèi)容或者功能進(jìn)行調(diào)整,但是不需要修改原始對象結(jié)構(gòu),理解了不???
還可以理解為,我們不去修改已有的類,而是通過創(chuàng)建另外一個(gè)裝飾器類,通過這個(gè)裝飾器類去動態(tài)的擴(kuò)展其需要修改的內(nèi)容。而它的好處也是顯而易見的,如下:
- 1、我們可以保證類的層次不會因過多而發(fā)生混亂。
- 2、當(dāng)我們需求的修改很小時(shí),不用改變原有的數(shù)據(jù)結(jié)構(gòu)。
我們來看下《PHP設(shè)計(jì)模式》里面的一個(gè)案例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
/** * 被修飾類 現(xiàn)在的需求: 要求能夠動態(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)換成大寫 } } } //客戶端測試 $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(); |
來看一個(gè)比較通俗但是比較簡單的案例:
- 設(shè)計(jì)一個(gè)UserInfo類,里面有UserInfo數(shù)組,用于存儲用戶名信息
- 通過addUser來添加用戶名
- getUserList方法將打印出用戶名信息
- 現(xiàn)在需要將添加的用戶信息變成大寫的,我們需要不改變原先的類,并且不改變原先的數(shù)據(jù)結(jié)構(gòu)
- 我們設(shè)計(jì)了一個(gè)UserInfoDecorate類來完成這個(gè)需求的操作,就像裝飾一樣,給原先的數(shù)據(jù)進(jìn)行了裝修
- 裝飾器模式有些像適配器模式,但是一定要注意,裝飾器主要是不改變現(xiàn)有對象數(shù)據(jù)結(jié)構(gòu)的前提
代碼如下:
UserInfo.php
1
2
3
4
5
6
7
8
9
10
11
12
|
//裝飾器模式,對已有對象的部分內(nèi)容或者功能進(jìn)行調(diào)整,但是不需要修改原始對象結(jié)構(gòu),可以使用裝飾器設(shè)計(jì)模式 class UserInfo { public $userInfo = array (); public function addUser( $userInfo ) { $this ->userInfo[] = $userInfo ; } public function getUserList() { print_r( $this ->userInfo); } } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
//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(); |
到此,咱們應(yīng)該是對于裝飾器模式有了一個(gè)大概的了解,接下來咱們看一下構(gòu)建裝飾器模式的案例,網(wǎng)上的,先來看目錄結(jié)構(gòu):
|decorator #項(xiàng)目根目錄
|--Think #核心類庫
|----Loder.php #自動加載類
|----decorator.php #裝飾器接口
|----colorDecorator.php #顏色裝飾器
|----sizeDecorator.php #字體大小裝飾器
|----echoText.php #被裝飾者
|--index.php #單一的入口文件
完事就是來構(gòu)建裝飾器接口,Think/decorator.php,如下:
1
2
3
4
5
6
7
8
9
10
11
|
<?php /** * 裝飾器接口 * Interface decorator * @package Think */ namespace Think; interface decorator{ public function beforeDraw(); public function afterDraw(); } |
再來就是顏色裝飾器 Think/colorDecorator.php,如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<?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,如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<?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,如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
<?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(); } } } |
再來個(gè)自動加載 Think/Loder.php,如下:
1
2
3
4
5
6
7
|
<?php namespace Think; class Loder{ static function autoload( $class ){ require BASEDIR . '/' . str_replace ( '\\' , '/' , $class ) . '.php' ; } } |
最后就是入口文件index.php了,如下:
1
2
3
4
5
6
7
8
9
10
11
12
|
<?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(); |
咱最后再來一個(gè)案例啊,就是Web服務(wù)層 —— 為 REST 服務(wù)提供 JSON 和 XML 裝飾器,來看代碼:
RendererInterface.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<?php namespace DesignPatterns\Structural\Decorator; /** * RendererInterface接口 */ interface RendererInterface { /** * render data * * @return mixed */ public function renderData(); } |
Webservice.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
<?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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
<?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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
<?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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
<?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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
<?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程序設(shè)計(jì)有所幫助。
原文鏈接:https://blog.csdn.net/luyaran/article/details/82883411