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

本文详细介绍了装饰器设计模式的概念及应用场景,通过PHP代码示例展示了如何为现有对象动态增加新功能,而不影响其他对象。装饰器模式允许在不修改原始类的基础上扩展对象功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

装饰器设计模式

什么是装饰器模式

装饰器模式就是对一个已有的结构增加装饰。装饰模式是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。

何时使用装饰器

基本说来, 如果想为现有对象增加新功能而不想影响其他对象, 就可以使用装饰器模式.

装饰器类图

装饰器的组成

  1. Component接口:定义一个对象接口,以规范准备接受附加责任的对象。
  2. Decorator接口:装饰器接口
  3. ConcreteComponent :具体组件角色,即将要被装饰增加功能的类
  4. ConcreteDecorator :具体装饰器,向组件添加职责

代码

Component接口

<?php 
namespace Test;
abstract class Component
{
   abstract public function operation(); 
}

Decorator

<?php
namespace Test;
abstract class Decorator extends Component
{
    protected $component;
    public function __construct(Component $component)
    {
        $this->component = $component;
    }
    public function operation()
    {
        $this->component->operation();
    }
    abstract public function before();
    abstract public function after();
}

ConcreteComponent

<?php
namespace Test;

class ConcreteComponent extends Component
{

    public function operation()
    {
        echo "hello world!!!!";
    }
}

ConcreteDecoratorA 添加了before和after方法,即在原有操作的基础上之前和之后又添加了职责

<?php
namespace Test;
class ConcreteDecoratorA extends Decorator
{
    public function __construct(Component $component)
    {
        parent::__construct($component);
    }

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

    public function before()
    {
        // TODO: Implement before() method.
        echo "before!!!";
    }

    public function after()
    {
        // TODO: Implement after() method.
        echo "after!!!";
    }
}

CLient主要用来实例化装饰器

<?php
namespace Test;
class Client
{
    /**
     *
     */
    public static function main() {
        $decoratorA = new ConcreteDecoratorA(new ConcreteComponent());
        $decoratorA->operation();
        $decoratorB=new ConcreteDecoratorA($decoratorA);
        $decoratorB->operation();
    }
}

调用Clien main()方法结果

before!!!hello world!!!!after!!!before!!!before!!!hello world!!!!after!!!after!!!

转载于:https://my.oschina.net/leisured/blog/600338

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值