设计模式——组合模式

组合模式(Composite Pattern)是一种结构型设计模式,它的主要目标是将对象组织到树形结构中,并且能够以统一的方式处理单个对象和组合对象。这种模式使得客户端可以一致地对待单个对象以及对象的集合。

原理

  • 抽象组件(Component): 定义所有组件共有的接口,包括叶子节点(Leaf)和容器节点(Composite)都继承自这个接口。
  • 叶子组件(Leaf): 是组合中的基本元素,它没有子组件,实现了抽象组件定义的操作。
  • 容器组件(Composite): 包含多个子组件,每个子组件都是一个抽象组件的实例;容器组件提供管理其子组件的方法,并实现与抽象组件相同的接口,以便客户端能一致地访问叶节点和容器节点。

Java代码示例

java 复制代码
// 抽象组件
public abstract class Component {
    public abstract void add(Component component);
    public abstract void remove(Component component);
    public abstract void operation();
}

// 叶子组件(例如:文本文件)
public class Leaf extends Component {
    @Override
    public void add(Component component) {
        throw new UnsupportedOperationException("Leaf doesn't support adding components");
    }

    @Override
    public void remove(Component component) {
        throw new UnsupportedOperationException("Leaf doesn't support removing components");
    }

    @Override
    public void operation() {
        System.out.println("Executing operation on a leaf component.");
    }
}

// 容器组件(例如:目录)
public class Composite extends Component {
    private List<Component> children = new ArrayList<>();

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

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

    @Override
    public void operation() {
        for (Component child : children) {
            child.operation();
        }
        System.out.println("Executing operation on a composite component and its children.");
    }
}

// 使用示例
public class Client {
    public static void main(String[] args) {
        // 创建叶子节点
        Component leaf1 = new Leaf();
        Component leaf2 = new Leaf();

        // 创建容器节点并添加叶子节点
        Composite composite = new Composite();
        composite.add(leaf1);
        composite.add(leaf2);

        // 对单个叶子和组合执行操作
        leaf1.operation();
        composite.operation();
    }
}

想象一下你正在管理一家公司,这家公司由员工组成,有些员工直接向你报告(叶子节点),有些员工是团队领导,他们手下还有其他员工(容器节点)。组合模式允许你对每位员工或整个团队下达命令时使用相同的方式,无论是单独与某位员工交谈,还是召开团队会议进行沟通。

应用场景

  • 文件系统中的目录和文件结构:目录可以包含文件和其他目录,而文件则没有子项。
  • 组合图形对象,如图形编辑器中的图形及其组合(组)。
  • HTML文档结构,其中元素可以嵌套其他元素形成层级结构。

适用性

  • 需要表示部分-整体层次结构的问题域。
  • 客户端需要一致地处理单个对象和对象集合的情况。
  • 想要简化在复杂对象树中进行操作的代码时。
相关推荐
Zane19942 天前
一个 new 就能创建对象,为什么还要拆出单例、工厂、建造者、原型四种模式?
设计模式
怕浪猫2 天前
一行命令复刻爆款视频,我把 Hypit 从安装跑到了出片
人工智能·设计模式·程序员
Zane19943 天前
函数式编程里的函数,其实不是你天天写的那个函数——三大编程范式的边界在哪
设计模式
Zane19944 天前
策略模式现在该不该上?一次讲清楚过度设计和设计不足怎么找平衡
设计模式
她说..4 天前
常见设计模式-模板方法模式
java·spring·设计模式·springboot
xiaofeiyang1504 天前
第六章 · 桥接 — 三支毛笔,画出九种颜色
设计模式
Shadow(⊙o⊙)5 天前
OTOL设计模式 One Thread One Loop
服务器·网络·设计模式
sarasuki5 天前
如何让LLM 能在半夜偷偷打开网易云呢?
人工智能·设计模式·agent
小王师傅665 天前
【设计模式】装饰模式(四):框架源码实战——从 Java I/O 到 Spring 到 MyBatis
java·设计模式
执明wa6 天前
Android RecyclerView 多类型, 多种 Item
android·xml·开发语言·设计模式·android studio