PHP设计模式系列(二):装饰模式
来源:互联网 发布:js同源策略和跨越请求 编辑:程序博客网 时间:2024/05/20 05:27
装饰模式
装饰模式(Decorator Pattern) :动态地给一个对象增加一些额外的职责(Responsibility),就增加对象功能来说,装饰模式比生成子类实现更为灵活。其别名也可以称为包装器(Wrapper),与适配器模式的别名相同,但它们适用于不同的场合。根据翻译的不同,装饰模式也有人称之为“油漆工模式”,它是一种对象结构型模式。
模式结构
装饰模式包含如下角色:
- Component: 抽象构件
- ConcreteComponent: 具体构件
- Decorator: 抽象装饰类
- ConcreteDecorator: 具体装饰类
结构图
PHP代码实现
<?php//Component类abstract class Component{ abstract public function operation();}//ConcreteComponent类class ConcreteComponent extends Component{ public function operation() { var_dump('具体对象操作'); }}//Decorator类abstract class Decorator extends Component{ public function setComponent($component){ $this->component=$component; } public function operation() { if($this->component!=null){ $this->component->operation(); } }}//ConcreteDecoratorA类class ConcreteDecoratorA extends Decorator{ public function operation() { parent::operation(); var_dump('装饰对象A的操作'); }}//ConcreteDecoratorB类class ConcreteDecoratorB extends Decorator{ public function operation() { parent::operation(); self::addBehavior(); var_dump('装饰对象B的操作'); } public function addBehavior() { var_dump('装饰对象B独有操作'); }}$a=new ConcreteComponent();$b1=new ConcreteDecoratorA();$b2=new ConcreteDecoratorB();$b1->setComponent($a);$b2->setComponent($b1);$b2->operation();
运行结果
string '具体对象操作' (length=18)string '装饰对象A的操作' (length=22)string '装饰对象B独有操作' (length=25)string '装饰对象B的操作' (length=22)
0 0
- PHP设计模式系列(二):装饰模式
- 【设计模式】之装饰器模式(二)-PHP
- PHP设计模式系列 - 装饰器
- PHP设计模式系列 - 装饰器
- PHP设计模式系列 - 装饰器
- 设计模式系列-装饰模式
- 装饰模式----设计模式系列
- 设计模式(二):装饰器模式
- 设计模式(二)装饰者模式
- PHP设计模式:装饰模式
- PHP设计模式系列(二十):中介者模式
- PHP设计模式系列(二十一):享元模式
- PHP设计模式系列(二十二):解释器模式
- PHP设计模式系列(二十三):访问者模式
- 设计模式系列之二:装饰者模式(Decorator Pattern)
- 设计模式(二)__装饰设计模式
- 二十、装饰设计模式
- 设计模式学习系列七:装饰模式(Decorator)
- springmvc(七)---RESTful的应用
- JAVA系统开发关键技术简介
- 剑指offer-面试题55-字符流中第一个不重复的字符
- 错误代码为 0x80072EFD,可在需要时使用 win10应用商店问题
- 5.剑指offer-链表复制
- PHP设计模式系列(二):装饰模式
- ubuntu配置环境
- C++ RTTI的简单实现(一)
- Maven项目不能部署到Tomcat
- OKHttp使用详解
- 关于棋牌游戏遇到的问题解决日志1
- 在salesforce中更换自定义app的logo
- 消息队列
- Dynamics CRM2016 通过web api来调用自定义action之global action