php之装饰者模式

装饰者模式概念

动态地将责任附加到对象上,若要扩展功能,装饰者提供了比继承更有弹性的替代方案

装饰者模式结构图

clipboard.png

装饰者角色

1.被装饰者基类(Compoent):对象组件
2.待装饰对象(ConcreteComponent):具体组件角色,即将要被装饰增加功能的类
3.装饰者基类(Decorator):需要定义一个与组件接口一致的接口,并持有一个Component对象,该对象其实就是被装饰的对象。
4.具体装饰者(ConcreteDecorator):现具体要向被装饰对象添加的功能。用来装饰具体的组件对象或者另外一个具体的装饰器对象

实例代码

<?php


//被装饰者基类
interface Component{
    public function  operation();
}

//装饰者基类
abstract class Decorator implements Component{
    protected $component;

    public function __construct(Component $component)
    {
        $this->component = $component;
    }

    public function operation()
    {
        $this->component->operation();
    }
}


//具体装饰者类
class ConcreteComponent implements Component{
    public function operation(){
        return 'do operation';
    }
}

//具体装饰者a
class ConcreteDecoratorA extends Decorator{

    public function __construct(Component $component)
    {
        parent::__construct($component);
    }

    public function operation()
    {
        parent::operation();
        $this->addOperationA();
    }

    public function addOperationA(){
        return 'add operation a';
    }
}

//具体装饰者类b
class ConcreteDecoratorB extends Decorator{

    public function __construct(Component $component)
    {
        parent::__construct($component);
    }

    public function operation()
    {
        parent::operation(); 
        $this->addOperationB();
    }

    public function addOperationB(){
        echo 'add operation b';
    }
}

$decoratorA = new ConcreteDecoratorA(new ConcreteComponent());
$decoratorA->operation();

总结

1.装饰者和被装饰者对象有相同的超类型
2.你可以用一个或者多个装饰者包装一个对象
3.既然装饰者和被装饰者对象有相同的超类,所以在任何需要原始对象(被包装的)的场合,可以用装饰过的对象替换他
4.(关键点)装饰者可以在委托被装饰者的行为之前/之后,加上自己的行为,已达到特地的目的
5.对象可以在任何时候被装饰,所以可以在运行时动态的、不限量的用你喜欢的装饰者来装饰对象

参考文献《head first 设计模式》

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值