当前位置:首页 > PHP

php实现组合模式

2026-02-15 18:32:23PHP

组合模式简介

组合模式(Composite Pattern)是一种结构型设计模式,允许将对象组合成树形结构以表示“部分-整体”的层次关系。客户端可以统一处理单个对象和组合对象,无需关心具体类型。

适用场景

  • 需要表示对象的层次结构(如文件系统、菜单树)。
  • 希望客户端以统一方式处理单个对象和组合对象。

PHP实现步骤

定义抽象组件

抽象组件声明组合中所有对象的通用接口,可以是抽象类或接口。

<?php
abstract class Component {
    protected $name;

    public function __construct($name) {
        $this->name = $name;
    }

    abstract public function add(Component $component);
    abstract public function remove(Component $component);
    abstract public function display($depth);
}

实现叶子组件

叶子组件是组合中的基本元素,没有子组件。

class Leaf extends Component {
    public function add(Component $component) {
        throw new Exception("Cannot add to a leaf");
    }

    public function remove(Component $component) {
        throw new Exception("Cannot remove from a leaf");
    }

    public function display($depth) {
        echo str_repeat("-", $depth) . $this->name . "\n";
    }
}

实现复合组件

复合组件包含子组件,通常存储子组件集合并实现操作逻辑。

class Composite extends Component {
    private $children = [];

    public function add(Component $component) {
        $this->children[] = $component;
    }

    public function remove(Component $component) {
        $index = array_search($component, $this->children);
        if ($index !== false) {
            unset($this->children[$index]);
        }
    }

    public function display($depth) {
        echo str_repeat("-", $depth) . $this->name . "\n";
        foreach ($this->children as $child) {
            $child->display($depth + 2);
        }
    }
}

客户端使用示例

客户端通过抽象接口操作组合结构,无需区分叶子或复合组件。

$root = new Composite("Root");
$root->add(new Leaf("Leaf A"));
$root->add(new Leaf("Leaf B"));

$branch = new Composite("Branch X");
$branch->add(new Leaf("Leaf XA"));
$branch->add(new Leaf("Leaf XB"));

$root->add($branch);
$root->display(1);

输出结果

执行后输出树形结构:

php实现组合模式

-Root
---Leaf A
---Leaf B
---Branch X
-----Leaf XA
-----Leaf XB

关键点

  • 透明性:所有组件(叶子/复合)实现相同接口,客户端无需类型判断。
  • 递归组合:复合组件的操作(如display())递归调用子组件。
  • 异常处理:叶子组件直接禁止不支持的操作(如add())。

通过组合模式,可以灵活扩展层次结构,同时保持代码简洁性。

标签: 组合模式
分享给朋友:

相关文章

vue实现的两种模式

vue实现的两种模式

Vue 实现的两种模式 Vue.js 主要支持两种实现模式:单文件组件(SFC)和运行时编译模式。这两种模式适用于不同的开发场景和需求。 单文件组件(SFC)模式 单文件组件是 Vue.js 最常用…

如何启用react并发模式

如何启用react并发模式

启用 React 并发模式的方法 React 并发模式(Concurrent Mode)是 React 18 引入的一项功能,允许应用在渲染过程中保持响应性。以下是启用并发模式的步骤: 安装 Rea…

ReAct模式实现原理

ReAct模式实现原理

ReAct模式的基本概念 ReAct(Reasoning and Acting)是一种结合推理(Reasoning)和行动(Acting)的智能决策框架,旨在通过动态交互提升模型的任务解决能力。其核心…

react实现mvvm模式

react实现mvvm模式

React 实现 MVVM 模式的方法 MVVM(Model-View-ViewModel)是一种前端架构模式,通过数据绑定实现视图与逻辑的分离。React 本身基于单向数据流设计,但可以通过以下方式…

php实现模式

php实现模式

PHP 实现设计模式的方法 设计模式是解决特定问题的可重用方案,PHP 中实现设计模式可以提升代码的可维护性和扩展性。以下是几种常见设计模式的实现方式。 单例模式 单例模式确保一个类只有一个实例,并…

js实现单例模式

js实现单例模式

单例模式的基本概念 单例模式是一种设计模式,确保一个类只有一个实例,并提供全局访问点。在JavaScript中,可以通过多种方式实现单例模式。 使用对象字面量 最简单的单例实现方式是直接使用对象字面…