当前位置:首页 > PHP

php实现组合模式

2026-02-15 18:32:23PHP

组合模式简介

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

适用场景

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

PHP实现步骤

定义抽象组件

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

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";
    }
}

实现复合组件

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

php实现组合模式

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);

输出结果

执行后输出树形结构:

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

关键点

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

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

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

相关文章

vue实现sku组合

vue实现sku组合

Vue实现SKU组合的方法 SKU(Stock Keeping Unit)是商品库存管理的基本单位,通常由多个属性组合而成。在电商系统中,实现SKU组合可以帮助用户选择商品的不同属性组合,并实时显示库…

vue 单选组合 实现

vue 单选组合 实现

Vue 单选组合实现 在 Vue 中实现单选组合可以通过多种方式完成,常见的方法包括使用原生 HTML 的 <input type="radio"> 结合 Vue 的数据绑定,或使用第三方…

vue采用哪种模式实现

vue采用哪种模式实现

Vue 采用的模式 Vue 主要采用 MVVM(Model-View-ViewModel)模式 实现数据与视图的绑定和交互。以下是其核心特点: Model(模型):代表数据层,通常是 Jav…

react实现mvvm模式

react实现mvvm模式

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

react实现组合拖拽

react实现组合拖拽

React 实现组合拖拽 在 React 中实现组合拖拽功能可以通过多种方式完成,常见的方法是使用第三方库如 react-dnd 或 react-beautiful-dnd。以下是两种主要实现方式:…

php实现组合排序 代码实现

php实现组合排序 代码实现

PHP实现组合排序代码 组合排序通常指按照多个字段或条件对数据进行排序。以下是几种常见的PHP实现方式: 使用usort自定义排序函数 $data = [ ['name' => 'Jo…