温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

什么是Java组合模式

发布时间:2026-07-24 14:09:27 来源:亿速云 阅读:88 作者:小樊 栏目:编程语言

Java 组合模式(Composite Pattern)结构型设计模式 的一种,用于把一组相似的对象当作一个单一对象来处理,从而以统一的方式处理单个对象对象组合


一、组合模式的核心思想

“树形结构 + 统一接口”

组合模式常用于表示:

  • 部分-整体(Part-Whole) 的层次结构
  • 如:文件夹与文件、菜单与菜单项、部门与员工等

✅ 目标:
让客户端对单个对象和组合对象的使用具有一致性


二、组合模式的角色组成

角色 说明
Component(抽象组件) 定义统一接口,声明公共操作
Leaf(叶子节点) 表示叶子对象,没有子节点
Composite(组合节点) 拥有子组件,实现组件接口,并管理子组件
Client(客户端) 通过 Component 接口操作对象

三、UML 结构示意

Component
  ↑        ↑
Leaf   Composite
            |
        children

四、经典示例:文件系统

1️⃣ 抽象组件(Component)

public abstract class FileComponent {
    protected String name;

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

    public abstract void display();
}

2️⃣ 叶子节点(Leaf)

public class File extends FileComponent {

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

    @Override
    public void display() {
        System.out.println("文件:" + name);
    }
}

3️⃣ 组合节点(Composite)

import java.util.ArrayList;
import java.util.List;

public class Directory extends FileComponent {

    private List<FileComponent> children = new ArrayList<>();

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

    public void add(FileComponent component) {
        children.add(component);
    }

    public void remove(FileComponent component) {
        children.remove(component);
    }

    @Override
    public void display() {
        System.out.println("目录:" + name);
        for (FileComponent child : children) {
            child.display();
        }
    }
}

4️⃣ 客户端使用

public class Client {
    public static void main(String[] args) {

        File f1 = new File("a.txt");
        File f2 = new File("b.txt");

        Directory dir = new Directory("文档");
        dir.add(f1);
        dir.add(f2);

        Directory root = new Directory("根目录");
        root.add(dir);

        root.display();
    }
}

五、组合模式的优点

统一处理对象与对象组合
符合开闭原则(新增节点类型方便)
适合树形结构,结构清晰


六、组合模式的缺点

❌ 设计较复杂
❌ 叶子节点可能被迫实现不需要的方法(如 add()
❌ 过度使用会导致系统抽象层次过多


七、适用场景

✅ 需要表示 树形结构的对象
✅ 希望对 单个对象和组合对象一视同仁
✅ 如:

  • 文件系统
  • 菜单系统
  • 组织架构
  • UI 组件树

八、一句话总结

组合模式让“单个对象”和“组合对象”拥有相同的接口,从而可以用一致的方式处理它们。

如果你愿意,我也可以帮你:

  • 菜单系统 再讲一遍
  • 对比 组合模式 vs 装饰器模式
  • 分析 Spring / 源码中的组合模式应用
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI