全球今热点:PHP面向对象的设计模式-装饰器模式

时间:2023-04-29 06:33:47 来源: 腾讯云


(资料图片仅供参考)

简介

装饰器模式是一种结构型设计模式,它允许您在运行时将行为添加到对象上,而不是在编译时将行为固定在对象上。这种模式通常用于需要大量动态扩展的场景,例如构建复杂的用户界面。

UML 类图

以下是装饰器模式的 UML 类图:

ComponentInterface <|-- ConcreteComponent                   |                   +-- DecoratorInterface <|-- ConcreteDecoratorA                                           +-- ConcreteDecoratorB

在上面的 UML 类图中,ComponentInterface 表示被装饰的对象的接口,ConcreteComponent 是实现该接口的具体对象,DecoratorInterface 是装饰器的接口,ConcreteDecoratorA 和 ConcreteDecoratorB 是具体的装饰器类。

组件

组件是我们想要扩展的对象。下面是一个示例:

interface ComponentInterface {    public function operation();}class ConcreteComponent implements ComponentInterface {    public function operation() {        return "ConcreteComponent";    }}

在上面的代码中,我们定义了 ComponentInterface 接口,它有一个名为 operation 的方法。我们还定义了一个名为 ConcreteComponent 的具体实现,它实现了 ComponentInterface 接口并实现了 operation 方法。

装饰器

装饰器是具有与组件相同的接口的类,它通过在组件上添加额外的行为来扩展其功能。下面是一个示例:

interface DecoratorInterface extends ComponentInterface {}class ConcreteDecoratorA implements DecoratorInterface {    protected $component;    public function __construct(ComponentInterface $component) {        $this->component = $component;    }    public function operation() {        return "ConcreteDecoratorA(" . $this->component->operation() . ")";    }}class ConcreteDecoratorB implements DecoratorInterface {    protected $component;    public function __construct(ComponentInterface $component) {        $this->component = $component;    }    public function operation() {        return "ConcreteDecoratorB(" . $this->component->operation() . ")";    }}

在上面的代码中,我们定义了一个名为 DecoratorInterface 的接口,它扩展了 ComponentInterface 接口。然后我们定义了两个具体的装饰器:ConcreteDecoratorA 和 ConcreteDecoratorB。这两个类都实现了 DecoratorInterface 接口,并且都有一个名为 component 的成员变量,它们分别用于存储被装饰的组件。

使用装饰器模式

使用装饰器模式时,您需要首先创建一个具体的组件对象,然后使用一个或多个装饰器对象来扩展其功能。下面是一个示例:

$component = new ConcreteComponent();$decoratorA = new ConcreteDecoratorA($component);$decoratorB = new ConcreteDecoratorB($decoratorA);echo $decoratorB->operation();

在上面的代码中,我们首先创建了一个具体的组件对象 ConcreteComponent。然后我们使用 ConcreteDecoratorA 对象来扩展 ConcreteComponent 的功能,并将其存储在 $decoratorA 变量中。接着,我们使用 ConcreteDecoratorB 对象来进一步扩展 $decoratorA 的功能,并将其存储在 $decoratorB 变量中。最后,我们调用 $decoratorB 的 operation 方法来执行装饰后的操作。

标签:

相关文章

社会面清零后第十天,三问吉林省复工复产怎样了

新华社长春4月23日电 题:社会面清零后第十天,三问吉林省复工复产怎样了 新华社记者段续、张建、赵丹丹...

来源:2022-04-24

青海海北州门源县发生3.9级地震 震源深度10千米

4月23日电 据国家地震台网官方微博消息,中国地震台网正式测定:04月23日22时07分在青海海北州门源县(...

来源:2022-04-24

山西太原万柏林区报告1例无症状感染者 公布行程轨迹

(抗击新冠肺炎)山西太原万柏林区报告1例无症状感染者 公布行程轨迹 太原4月23日电 (记者 李新锁)山西...

来源:2022-04-24

上海战疫:从严从重从快查处食品安全违法行为

(抗击新冠肺炎)上海战疫:从严从重从快查处食品安全违法行为 上海4月23日电 (记者 许婧)近日,上海出现...

来源:2022-04-24

杭州本轮疫情已发现98例阳性感染者 有进一步扩散可能

杭州4月23日电(张煜欢 崔倩娴)23日,记者从杭州市新冠肺炎疫情防控工作新闻发布会上获悉,截至23日18时...

来源:2022-04-24

精彩推送

X 关闭

X 关闭