结构型模式 - 组合模式 (Composite Pattern)

结构型模式 - 组合模式 (Composite Pattern)

组合模式是一种结构型设计模式,它允许你将对象组合成树形结构以表示 "部分 - 整体" 的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。


经典的例子就是树形结构,里面可以是文件和文件夹的组合,文件夹还可以再往下组合文件夹和文件.

java 复制代码
// 抽象组件类,定义文件和文件夹的公共操作
abstract class FileSystemComponent {
    protected String name;

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

    // 获取组件名称
    public String getName() {
        return name;
    }

    // 显示组件信息,具体实现由子类完成
    public abstract void display();

    // 以下方法在叶子节点(文件)中不做实际操作,在组合节点(文件夹)中实现
    public void add(FileSystemComponent component) {
        throw new UnsupportedOperationException("不支持该操作");  // 默认抛出异常, 只有文件夹类型的去重写就行
    }

    public void remove(FileSystemComponent component) {
        throw new UnsupportedOperationException("不支持该操作");
    }

    public FileSystemComponent getChild(int index) {
        throw new UnsupportedOperationException("不支持该操作");
    }
}
java 复制代码
// 叶子节点类,代表文件
class File extends FileSystemComponent {
    public File(String name) {
        super(name);
    }

    // 显示文件信息
    @Override
    public void display() {
        System.out.println("文件: " + getName());
    }
}
java 复制代码
import java.util.ArrayList;
import java.util.List;

// 组合节点类,代表文件夹
class Folder extends FileSystemComponent {
    private List<FileSystemComponent> children = new ArrayList<>();

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

    // 显示文件夹及其子组件信息
    @Override
    public void display() {
        System.out.println("文件夹: " + getName());
        for (FileSystemComponent component : children) {
            System.out.print("  ");
            component.display();
        }
    }

    // 添加子组件
    @Override
    public void add(FileSystemComponent component) {
        children.add(component);
    }

    // 移除子组件
    @Override
    public void remove(FileSystemComponent component) {
        children.remove(component);
    }

    // 获取指定索引的子组件
    @Override
    public FileSystemComponent getChild(int index) {
        return children.get(index);
    }
}

父类默认给 add, remove, getChild 抛出异常, 文件夹类重写父类 add, remove, getChild, 来达到文件夹类有这些方法, 而文件类没有.

这种编码形式可以借鉴, 可以在一定程度上规避一些问题.

相关推荐
AI人工智能+电脑小能手28 分钟前
大白话说Java设计模式-14-适配器模式(业务实战篇)
java·设计模式·适配器模式·系统兼容·多渠道对接
略略略咯咯9 小时前
(总结)设计模式
设计模式
Cosolar1 天前
DeepSeek Harness 理解 Harness 的设计哲学 - 可组合的插件运行时
人工智能·设计模式·架构
Nebula_g1 天前
JavaSE基础语法:特殊类(特殊情景下的设计模式)
java·开发语言·设计模式
George_Ye2 天前
同一本书,一人一份:我如何设计 AI 个性化扫书报告
设计模式
莫得感情 o2 天前
设计模式 22 · 三个冷门模式:中介者、访问者、解释器
java·设计模式
AI人工智能+电脑小能手3 天前
大白话说Java设计模式-08-建造者模式(业务实战篇)
java·设计模式·建造者模式·架构设计·对象构建
AustinXu3 天前
从 Claude Code 到 Claude Tag,Harness Engineering 走到了组织这一层
设计模式·团队管理
剧中有戏3 天前
单例模式从入门到精通:一个数据库连接池的完整剖析
设计模式
胡萝卜术3 天前
编译期与运行期的双重防线:从 TypeScript 类型之争到 LLM 输出的自动化择优
前端·设计模式·面试