Skip to content

组合模式

基础概念

什么是组合模式?

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

使用场景

  • 表示对象的部分-整体层次结构
  • 希望用户忽略组合对象与单个对象的不同

优点

  • 定义了包含基本对象和组合对象的类层次结构
  • 简化客户端代码
  • 易于增加新类型的组件

缺点

  • 设计较为复杂
  • 不容易限制组合中的组件

实现方式

java
// 组件接口
public abstract class Component {
    protected String name;

    public Component(String name) {
        this.name = name;
    }

    public abstract void add(Component component);
    public abstract void remove(Component component);
    public abstract void display(int depth);
}

// 叶子节点
public class Leaf extends Component {
    public Leaf(String name) {
        super(name);
    }

    @Override
    public void add(Component component) {
        throw new UnsupportedOperationException();
    }

    @Override
    public void remove(Component component) {
        throw new UnsupportedOperationException();
    }

    @Override
    public void display(int depth) {
        System.out.println("-".repeat(depth) + name);
    }
}

// 组合节点
public class Composite extends Component {
    private List<Component> children = new ArrayList<>();

    public Composite(String name) {
        super(name);
    }

    @Override
    public void add(Component component) {
        children.add(component);
    }

    @Override
    public void remove(Component component) {
        children.remove(component);
    }

    @Override
    public void display(int depth) {
        System.out.println("-".repeat(depth) + name);
        for (Component component : children) {
            component.display(depth + 2);
        }
    }
}

// 使用(文件系统)
Component root = new Composite("根目录");
Component folder1 = new Composite("文件夹1");
Component folder2 = new Composite("文件夹2");
Component file1 = new Leaf("文件1.txt");
Component file2 = new Leaf("文件2.txt");

root.add(folder1);
root.add(folder2);
folder1.add(file1);
folder2.add(file2);

root.display(1);

练习题

  1. 组合模式的应用场景?
  2. 如何遍历组合结构?
  3. 组合模式和装饰器模式的区别?

Released under the MIT License.