设计模式学习(三)、装饰者模式

装饰者模式详解
本文介绍了装饰者模式的概念及其在PHP中的实现方式。装饰者模式允许在不改变原有对象的情况下为其添加新的职责,提供了比继承更灵活的替代方案。文中通过具体的PHP代码示例展示了如何通过装饰者模式为对象动态地添加功能。

1装饰者模式的概念:

动态的将责任附加到对象上。想要扩充功能,装饰者提供有利于继承的另一种选择。

2.装饰者模式的结构图

3.装饰者模式角色说明

组件(component)角色:定义ConcreteComponent和Decorator类要实现的方法,简单来说如果一个类继承于该类就具有装饰或被装饰能力。
具体组件(ConcreteComponent)角色:让Decorator对象为自己添加功能。
抽象装饰者(Decorator)角色:装饰者共同实现的类。
具体装饰者(ConcreteDecorator)角色:具有特定装饰功能的类,用来装饰ConcreteComponent类。

4.装饰者模式的实现

<?php
/**
 * 装饰者模式实例
 */
//抽象组件
 abstract Class Component
{
    public abstract  function operation();
}

//具体组件
class ConcreteComponent extends  Component
{
    public function operation()
    {
        echo 'it is concreteComponent';
    }
}

//抽象装饰者
abstract class Decorator extends  Component
{

}
//抽象装饰者

class ConcreteDecorator1 extends  Component
{
    public $component;
    public function __construct($component)
    {
        $this->$component = $component;
    }
    public function operation(){
       echo  $this->component->operation().'add concreteDecorator1';
    }
}
//抽象装饰者

class ConcreteDecorator2 extends  Component
{
    public $component;
    public function __construct($component)
    {
        $this->$component = $component;
    }
    public function operation(){
        echo  $this->component->operation().'add concreteDecorator2';
    }
}

//客户端使用
$c = new ConcreteComponent();
$d1 = new ConcreteDecorator1($c);
$d2 = new ConcreteDecorator2($d1);
$p->operation();

 

 

转载于:https://www.cnblogs.com/huixuexidezhu/p/5972249.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值