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

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

相关推荐
静水流深_沧海一粟17 小时前
04 | 别再写几十个参数的构造函数了——建造者模式
设计模式
StarkCoder17 小时前
从UIKit到SwiftUI的迁移感悟:数据驱动的革命
设计模式
阿星AI工作室1 天前
给openclaw龙虾造了间像素办公室!实时看它写代码、摸鱼、修bug、写日报,太可爱了吧!
前端·人工智能·设计模式
_哆啦A梦2 天前
Vibe Coding 全栈专业名词清单|设计模式·基础篇(创建型+结构型核心名词)
前端·设计模式·vibecoding
阿闽ooo5 天前
中介者模式打造多人聊天室系统
c++·设计模式·中介者模式
小米4965 天前
js设计模式 --- 工厂模式
设计模式
逆境不可逃5 天前
【从零入门23种设计模式08】结构型之组合模式(含电商业务场景)
线性代数·算法·设计模式·职场和发展·矩阵·组合模式
驴儿响叮当20105 天前
设计模式之状态模式
设计模式·状态模式
电子科技圈5 天前
XMOS推动智能音频等媒体处理技术从嵌入式系统转向全新边缘计算
人工智能·mcu·物联网·设计模式·音视频·边缘计算·iot
徐先生 @_@|||6 天前
安装依赖三方exe/msi的软件设计模式
设计模式