php设计模式之装饰模式应用案例详解

Erin ·
更新时间:2024-09-21
· 684 次阅读

本文实例讲述了php设计模式之装饰模式。分享给大家供大家参考,具体如下:

介绍

装饰者模式(Decorator Pattern)允许你向一个现有的对象添加新的功能,同时又不改变其结构。 这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。 这种模式创建了一个装饰类,用来包装原有的类,并在保持类方法签名完整性的前提下,提供了额外的功能。

主要角色

抽象构件(Component)角色:定义一个独享接口,以规范准备接收附加职责的对象,从而可以给这些对象动态的添加职责。 具体构件(Concrete Component)角色:定义一个将要接收附加职责的类。 装饰(Decorator)角色:持有一个指向Component对象的指针,并定义一个与Component接口一致的接口。 具体装饰(Concrete Decorator)角色:负责给构件对象增加附加的职责。

下面是使用装饰模式的一个简单实现:

class RequestHelper{} abstract class ProcessRequest{ abstract function process(RequestHelper $req); } class MainProcess extends ProcessRequest{ function process(RequestHelper $req) { print __CLASS__.": doing something useful with request\n"; } } abstract class DecorateProcess extends ProcessRequest{ protected $processRequest; function __construct(ProcessRequest $pr) { $this->processRequest = $pr; } }

和之前一样,我们定义了一个抽象基类(ProcessRequest)、一个具体的组件(MainProcess)和一个抽象装饰类(DecorateProcess)。 MainProcess::process()方法仅仅报告方法被调用,并没有其他功能。DecorateProcess为他的子类保存了一个ProcessRequest对象。下面是一些简单的具体装饰类:

class LogRequest extends DecorateProcess{ function process(RequestHelper $req) { print __CLASS__.": logging request\n"; $this->processRequest->process($req); } } class AuthenticateRequest extends DecorateProcess{ function process(RequestHelper $req) { print __CLASS__.": authenticating request\n"; $this->processRequest->process($req); } } class StructureRequest extends DecorateProcess{ function process(RequestHelper $req) { print __CLASS__.": structuring request\n"; $this->processRequest->process($req); } }

装饰类的每一个process()方法在调用引用的processRequest对象的Process()方法前输出一条信息。

现在我们可以在运行时合并这些类的对象,创建过滤器来对每一个请求按不同的顺序执行不同操作。下面的代码将所有具体类的对象组合成为一个过滤器:

$process = new AuthenticateRequest(new StructureRequest( new LogRequest( new MainProcess() ))); $process->process(new RequestHelper());

执行代码会得到下面的输出结果:

Authenticate
Request: authenticating request
StructureRequest: structuring request
LogRequest: logging request
MainProcess: doing something useful with request

优点:

装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个代替模式,装饰模式可以动态扩展一个实现类的功能。

缺点:

多层装饰比较负责。

更多关于PHP相关内容感兴趣的读者可查看本站专题:《php面向对象程序设计入门教程》、《PHP数组(Array)操作技巧大全》、《PHP基本语法入门教程》、《PHP运算与运算符用法总结》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家PHP程序设计有所帮助。

您可能感兴趣的文章:php设计模式 Adapter(适配器模式)PHP设计模式之适配器模式代码实例php适配器模式介绍学习php设计模式 php实现适配器模式PHP设计模式之适配器模式原理与用法分析PHP设计模式之适配器模式定义与用法详解php设计模式之工厂模式用法经典实例分析php设计模式之单例模式用法经典示例分析php设计模式之观察者模式定义与用法经典示例php设计模式之职责链模式定义与用法经典示例php设计模式之策略模式应用案例详解php设计模式之适配器模式原理、用法及注意事项详解



装饰模式 PHP

需要 登录 后方可回复, 如果你还没有账号请 注册新账号