通俗易懂设计模式(组合模式)

55 阅读2分钟

组合模式(Composite Pattern)是一种结构型设计模式,它允许将对象组合成树形结构以表示整体/部分层次结构。组合模式使得客户端可以统一对待单个对象和组合对象,从而使得客户端可以处理更复杂的结构。

组合模式的主要组成部分包括:

  1. 组件(Component):定义了一个接口,用于访问和管理组合对象中的元素。
  2. 叶子(Leaf):表示组合对象中的叶子节点,它不包含子节点。
  3. 容器(Container):表示组合对象中的容器节点,它包含子节点,并实现了组件接口。

组合模式的优点:

  1. 提高了代码的可扩展性:组合模式可以通过添加新的叶子节点和容器节点来扩展系统的功能,而不需要修改已有的代码。
  2. 提高了代码的可维护性:组合模式将复杂的结构分解为简单的叶子节点和容器节点,使得代码更加清晰和易于维护。

Java 实现组合模式的示例代码:

// 组件接口
public interface Component {
    void operation();
}

// 叶子节点
public class Leaf implements Component {
    @Override
    public void operation() {
        System.out.println("Leaf operation");
    }
}

// 容器节点
public class Container implements Component {
    private List<Component> children = new ArrayList<>();

    public void addChild(Component child) {
        children.add(child);
    }

    public void removeChild(Component child) {
        children.remove(child);
    }

    @Override
    public void operation() {
        System.out.println("Container operation");
        for (Component child : children) {
            child.operation();
        }
    }
}

// 客户端代码
public class Client {
    public static void main(String[] args) {
        Component leaf = new Leaf();
        Component container = new Container();

        container.addChild(leaf);
        container.addChild(new Leaf());

        container.operation();
    }
}

在这个示例中,我们定义了一个组件接口 Component,它包含了一个 operation() 方法。接着,我们定义了一个叶子节点类 Leaf,它实现了 Component 接口。然后,我们定义了一个容器节点类 Container,它也实现了 Component 接口,并持有一个子节点列表。在容器节点类中,我们提供了 addChild()removeChild() 方法来添加和删除子节点。

在客户端代码中,我们创建了一个叶子节点对象和一个容器节点对象,并将叶子节点对象添加到容器节点对象中。然后,我们调用容器节点对象的 operation() 方法,从而实现了叶子节点对象的 operation() 方法的调用。