- ubuntu12.04环境下使用kvm ioctl接口实现最简单的虚拟机
- Ubuntu 通过无线网络安装Ubuntu Server启动系统后连接无线网络的方法
- 在Ubuntu上搭建网桥的方法
- ubuntu 虚拟机上网方式及相关配置详解
CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.
这篇CFSDN的博客文章PHP设计模式之装饰器(装饰者)模式(Decorator)入门与应用详解由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.
本文实例讲述了PHP设计模式之装饰器(装饰者)模式(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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
/** * 被修饰类 现在的需求: 要求能够动态为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.php 。
1
2
3
4
5
6
7
8
9
10
11
12
|
//装饰器模式,对已有对象的部分内容或者功能进行调整,但是不需要修改原始对象结构,可以使用装饰器设计模式
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();
|
到此,咱们应该是对于装饰器模式有了一个大概的了解,接下来咱们看一下构建装饰器模式的案例,网上的,先来看目录结构:
|decorator #项目根目录 |--Think #核心类库 |----Loder.php #自动加载类 |----decorator.php #装饰器接口 |----colorDecorator.php #颜色装饰器 |----sizeDecorator.php #字体大小装饰器 |----echoText.php #被装饰者 |--index.php #单一的入口文件 。
完事就是来构建装饰器接口,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() {
//调用装饰器前置操作
$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,如下:
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'
);
//实例化输出类
$echo
=
new
\Think\echoText();
//增加装饰器
$echo
->addDecorator(
new
\Think\colorDecorator(
'red'
));
//增加装饰器
$echo
->addDecorator(
new
\Think\sizeDecorator(
'12'
));
//装饰方法
$echo
->index();
|
咱最后再来一个案例啊,就是Web服务层 —— 为 REST 服务提供 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;
/**
* 装饰器必须实现 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 。
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程序设计有所帮助.
原文链接:https://blog.csdn.net/luyaran/article/details/82883411 。
最后此篇关于PHP设计模式之装饰器(装饰者)模式(Decorator)入门与应用详解的文章就讲到这里了,如果你想了解更多关于PHP设计模式之装饰器(装饰者)模式(Decorator)入门与应用详解的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。
我之前让 dll 注入(inject)器变得简单,但我有 Windows 7,我用 C# 和 C++ 做了它,它工作得很好!但是现在当我在 Windows 8 中尝试相同的代码时,它似乎没有以正确的方
我正在尝试制作一个名为 core-splitter 的元素,该元素在 1.0 中已弃用,因为它在我们的项目中起着关键作用。 如果您不知道 core-splitter 的作用,我可以提供一个简短的描述。
我有几个不同的蜘蛛,想一次运行所有它们。基于 this和 this ,我可以在同一个进程中运行多个蜘蛛。但是,我不知道如何设计一个信号系统来在所有蜘蛛都完成后停止 react 器。 我试过了: cra
有没有办法在达到特定条件时停止扭曲 react 器。例如,如果一个变量被设置为某个值,那么 react 器应该停止吗? 最佳答案 理想情况下,您不会将变量设置为一个值并停止 react 器,而是调用
https://code.angularjs.org/1.0.0rc9/angular-1.0.0rc9.js 上面的链接定义了外部js文件,我不知道Angular-1.0.0rc9.js的注入(in
我正在尝试运行一个函数并将服务注入(inject)其中。我认为这可以使用 $injector 轻松完成.所以我尝试了以下(简化示例): angular.injector().invoke( [ "$q
在 google Guice 中,我可以使用函数 createInjector 创建基于多个模块的注入(inject)器。 因为我使用 GWT.create 在 GoogleGin 中实例化注入(in
我在 ASP.NET Core 1.1 解决方案中使用配置绑定(bind)。基本上,我在“ConfigureServices Startup”部分中有一些用于绑定(bind)的简单代码,如下所示: s
我在 Spring MVC 中设置 initBinder 时遇到一些问题。我有一个 ModelAttribute,它有一个有时会显示的字段。 public class Model { privat
我正在尝试通过jquery post发布knockoutjs View 模型 var $form = $('#barcodeTemplate form'); var data = ko.toJS(vm
如何为包含多态对象集合的复杂模型编写自定义模型绑定(bind)程序? 我有下一个模型结构: public class CustomAttributeValueViewModel { publi
您好,我正在尝试实现我在 this article 中找到的扩展方法对于简单的注入(inject)器,因为它不支持开箱即用的特定构造函数的注册。 根据这篇文章,我需要用一个假的委托(delegate)
你好,我想自动注册我的依赖项。 我现在拥有的是: public interface IRepository where T : class public interface IFolderReposi
我正在使用 Jasmine 测试一些 Angular.js 代码。为此,我需要一个 Angular 注入(inject)器: var injector = angular.injector(['ng'
我正在使用 Matlab 代码生成器。不可能包含代码风格指南。这就是为什么我正在寻找一个工具来“ reshape ”、重命名和重新格式化生成的代码,根据我的: 功能横幅约定 文件横幅约定 命名约定 等
这个问题在这里已经有了答案: Where and why do I have to put the "template" and "typename" keywords? (8 个答案) 关闭 8
我开发了一种工具,可以更改某些程序的外观。为此,我需要在某些进程中注入(inject)一个 dll。 现在我基本上使用这个 approach .问题通常是人们无法注入(inject) dll,因为他们
我想使用 swing、spring 和 hibernate 编写一个 java 应用程序。 我想使用数据绑定(bind)器用 bean 的值填充 gui,并且我还希望它反射(reflect) gui
我有这段代码,当两个蜘蛛完成后,程序仍在运行。 #!C:\Python27\python.exe from twisted.internet import reactor from scrapy.cr
要点是 Spring Batch (v2) 测试框架具有带有 @Autowired 注释的 JobLauncherTestUtils.setJob。我们的测试套件有多个 Job 类提供者。因为这个类不
我是一名优秀的程序员,十分优秀!