结构型 中等

组合模式

Composite Pattern

将对象组合成树形结构以表示"部分-整体"的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。

概述

组合模式是一种结构型设计模式,你可以使用它将对象组合成树状结构,并且能像使用独立对象一样使用它们。

适用场景

  • 当需要实现树状对象结构时
  • 当希望客户端代码以相同方式处理简单和复杂元素时

优点

  • +可以利用多态和递归以更方便的方式使用复杂树结构
  • +开闭原则:无需更改现有代码,就能在应用中添加新元素

缺点

  • 对于功能差异较大的类,提供公共接口可能会有困难
  • 在某些情况下,过度使用组合模式会导致代码更加复杂

结构

classDiagram class Component { <<interface>> +operation() string +add(Component) void +remove(Component) void +getChild(int) Component } class Leaf { +operation() string } class Composite { -children: List~Component~ +operation() string +add(Component) void +remove(Component) void +getChild(int) Component } class Client { +main() } Component <|-- Leaf Component <|-- Composite Composite o--> Component : children Client ..> Component : uses style Component fill:#e3f2fd,stroke:#1976d2,stroke-width:2px style Leaf fill:#e8f5e9,stroke:#388e3c,stroke-width:1px style Composite fill:#fff3e0,stroke:#f57c00,stroke-width:1px style Client fill:#f5f5f5,stroke:#616161,stroke-width:1px

交互演示

统一处理单个对象和组合对象
📁 RootComposite
📁 Folder1
📄 file1
📄 file2
📄 File3
统一操作

点击树中的节点,然后执行操作。组合模式让文件和文件夹可以被统一处理。

生活类比

组合模式就像是文件系统

文件系统

文件系统由文件和文件夹组成,文件夹可以包含文件和其他文件夹,形成树形结构。

代码实现

Example.java

实际应用

Java Swing

Java Swing 中的容器和组件使用组合模式。

Example.java

练习

1

组合模式的主要目的是什么?