PHP结构型模式之装饰器模式(php设计模型)没想到

随心笔谈9个月前发布 admin
202 00
🌐 经济型:买域名、轻量云服务器、用途:游戏 网站等 《腾讯云》特点:特价机便宜 适合初学者用 点我优惠购买
🚀 拓展型:买域名、轻量云服务器、用途:游戏 网站等 《阿里云》特点:中档服务器便宜 域名备案事多 点我优惠购买
🛡️ 稳定型:买域名、轻量云服务器、用途:游戏 网站等 《西部数码》 特点:比上两家略贵但是稳定性超好事也少 点我优惠购买

文章摘要

本文介绍了PHP中抽象组件和装饰器的设计模式。文章通过示例展示了如何通过接口和类的继承来实现组件的扩展功能。具体来说,文章定义了抽象组件接口`Component`,并实现了两个具体的组件`ConcreteComponent`。接着,通过抽象装饰器`Decorator`实现了组件的动态装饰功能,该装饰器通过继承组件并重写`operation`方法来调用基类的`operation`方法并添加额外的行为。文章还展示了如何通过装饰器逐步装饰组件,并最终调用`operation`方法来展示装饰后的功能。

<?php
// 抽象组件
interface Component
{
public function operation();
}
// 具体组件
class ConcreteComponent implements Component
{
public function operation()
{
echo “ConcreteComponent operation.\n”;
}
}
// 抽象装饰器
abstract class Decorator implements Component
{
protected $component;
public function __construct(Component $component)
{
$this->component=$component;
}
public function operation()
{
$this->component->operation();
}
}
// 具体装饰器A
class ConcreteDecoratorA extends Decorator
{
public function operation()
{
parent::operation();
$this->addedBehavior();
echo “ConcreteDecoratorA operation.\n”;
}
public function addedBehavior()
{
echo “Added behavior in ConcreteDecoratorA.\n”;
}
}
// 具体装饰器B
class ConcreteDecoratorB extends Decorator
{
public function operation()
{
parent::operation();
$this->addedBehavior();
echo “ConcreteDecoratorB operation.\n”;
}
public function addedBehavior()
{
echo “Added behavior in ConcreteDecoratorB.\n”;
}
}
// 客户端代码
$component=new ConcreteComponent();
$decoratorA=new ConcreteDecoratorA($component);
$decoratorB=new ConcreteDecoratorB($decoratorA);
$decoratorB->operation();

© 版权声明

相关文章