设计模式PHP版六 - 装饰器模式

<?php
/**
 * 定义一个接口
 * Interface Component
 */
interface Component
{
    public function operation();
}


/**
 * Class Decorator 装饰器
 */
abstract class Decorator implements Component
{
    /**
     * 服饰
     * @var $clothing
     */
    protected $clothing;

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

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


/**
 * Class Suit 西装装饰类
 */
class Suit extends Decorator
{
    public function __construct($clothing)
    {
        parent::__construct($clothing);
    }

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

    public function suit()
    {
        echo '穿西装 ';
    }
}


/**
 * Class Hat 帽子装饰类
 */
class Hat extends Decorator
{
    public function __construct($clothing)
    {
        parent::__construct($clothing);
    }

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

    public function hat()
    {
        echo '戴帽子 ';
    }
}


/**
 * Class Swimsuit 泳衣装饰类
 */
class Swimsuit extends Decorator
{
    public function __construct($clothing)
    {
        parent::__construct($clothing);
    }

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

    public function swimsuit()
    {
        echo '穿泳衣 ';
    }
}


/**
 * Class ConcreteComponent 具体组件类,要装饰的类
 */
class ConcreteComponent implements Component
{
    public function operation()
    {
        echo '裸体的人 ';
    }
}


$component = new ConcreteComponent();
$component->operation();

echo '<br>---------------------<br>';

/**
 * Suit继承了Decorator,当把$component传入时进入构造方法,走了parent::__construct,就是运行了父类的构造方法。
 * 此时,Decorator类里的$clothing就存储了$component对象。
 */
$suit = new Suit($component);
// 调用时是先运行了parent::operation(),也就是Decorator类里$component对象,再调用类自身的方法
$suit->operation(); // 输出 裸体的人 穿西装

echo '<br>---------------------<br>';

/**
 * 同上,只不过Decorator类里的$clothing变成了Suit($component)
 */
$hat = new Hat($suit);
// 调用时先是运行了parent::operation(),也就是Suit($component)->operation(),和上面的$suit->operation()效果是一样的
$hat->operation(); // 输出 裸体的人 穿西装 戴帽子

echo '<br>---------------------<br>';

$hatTwo = new Hat($component);
$hatTwo->operation();

echo '<br>---------------------<br>';

$swimsuit = new Swimsuit($component);
$swimsuit->operation();

/**
 * 其实就是实现了动态的对所要操作的一个很重要的类增加操作。假设如果是一个很复杂的类,你又不能轻易去改的情况下,在某个部分要给它增加后续的操作。
 * 你也许会想,那这样我直接继承然后调用不就完事了?干嘛整这么复杂?可你增加多个操作时,得一层一层的继承啊,当A继承B,B继承C,C继承D,输出ABCD,现在的需求是AD,中间就多了俩个类,如果更多的操作呢?
 * 而现在你只需将所有的装饰类继承装饰器类,将最高层的基类传入装饰类,就实现了"继承"的效果,而且是动态的。要用什么就装饰什么。
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值