结构型模式 - 组合模式 (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, 来达到文件夹类有这些方法, 而文件类没有.

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

相关推荐
星空寻流年1 小时前
设计模式第四章(组合模式)
设计模式·组合模式
笨手笨脚の1 小时前
设计模式-组合模式
设计模式·组合模式·结构型设计模式·设计模式之美
yujkss1 小时前
23种设计模式之【抽象工厂模式】-核心原理与 Java实践
java·设计模式·抽象工厂模式
PaoloBanchero4 小时前
Unity 虚拟仿真实验中设计模式的使用 ——命令模式(Command Pattern)
unity·设计模式·命令模式
大飞pkz4 小时前
【设计模式】桥接模式
开发语言·设计模式·c#·桥接模式
BeyondCode程序员6 小时前
设计原则讲解与业务实践
设计模式·架构
青草地溪水旁7 小时前
设计模式(C++)详解——迭代器模式(1)
c++·设计模式·迭代器模式
青草地溪水旁7 小时前
设计模式(C++)详解——迭代器模式(2)
java·c++·设计模式·迭代器模式
苍老流年7 小时前
1. 设计模式--工厂方法模式
设计模式·工厂方法模式
PaoloBanchero8 小时前
Unity 虚拟仿真实验中设计模式的使用 ——策略模式(Strategy Pattern)
unity·设计模式·策略模式