[PHP] 组合模式-结构型设计模式

以单个对象的方式来对待一组对象

有一个接口类,有一个需实现的方法,其他所有类都实现它,在一个组合类的实现方法中循环调用另外其他类的方法

有一个公共的接口类

interface Renderable
{
    public function render(): string;
}

组合类,也实现了接口

复制代码
class Form implements Renderable
{
    private array $elements;
    public function render(): string
    {
        //组合类里面循环调用其他类的同名方法
        foreach ($this->elements as $element) {
            $element->render();
        }
    }
    public function addElement(Renderable $element)
    {
        $this->elements[] = $element;
    }
}
复制代码

子项类,也实现了接口

复制代码
class InputElement implements Renderable
{
    public function render(): string
    {
    }
}
class TextElement implements Renderable
{
    public function render(): string
    {
    }
}
复制代码

使用的时候,像使用单一类一样使用组合类

$form = new Form();
$form->addElement(new TextElement());
$form->addElement(new InputElement());
$form->render();

 

posted @   唯一客服系统开发笔记  阅读(237)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2019-10-15 [Linux] 纯净ubuntu系统仓库更换为阿里云的源
2019-10-15 [日常] 解决docker拉取镜像速度慢的问题
2018-10-15 [PHP]算法-拼接最小字典序的实现
点击右上角即可分享
微信分享提示
1
chat with us