设计模式之组合模式

概念:将对象组合成树形结构以表示"部分------整体"的层次结构,使得用户对单个对象和组合对象的使用具有一致性。

组合模式有三个角色:

  • 抽象构件:定义公有属性和方法。
  • 叶子结点:树形结构的底层结点,没有子结点,实现抽象构件的所有操作。
  • 中间结点:叶子结点之前的结点,有子结点。

组合模式最经典的例子就是文件和文件夹结构。下面用一个这样的例子来帮助大家理解组合模式。

java 复制代码
public abstract class FileComponent {
    protected String name;
    public FileComponent(String name) {
        this.name = name;
    }
    public abstract void add(FileComponent component);
    public abstract void remove(FileComponent component);
    public abstract void display(int depth);
    public String getName() {
        return name;
    }
}

public class FileNode extends FileComponent {
    public FileNode(String name) {
        super(name);
    }
    @Override
    public void add(FileComponent component) {
        throw new UnsupportedOperationException("Cannot add components to a file.");
    }
    @Override
    public void remove(FileComponent component) {
        throw new UnsupportedOperationException("Cannot remove components from a file.");
    }
    @Override
    public void display(int depth) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < depth; i++) {
            sb.append("--");
        }
        System.out.println(sb + name);
    }
}

public class Directory extends FileComponent {
    private List<FileComponent> children;
    public Directory(String name) {
        super(name);
        children = new ArrayList<>();
    }
    @Override
    public void add(FileComponent component) {
        children.add(component);
    }
    @Override
    public void remove(FileComponent component) {
        children.remove(component);
    }
    @Override
    public void display(int depth) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < depth; i++) {
            sb.append("--");
        }
        System.out.println(sb + name);
        for (FileComponent child : children) {
            child.display(depth + 1);
        }
    }
}

public class Demo {
    public static void main(String[] args) {
        Directory root = new Directory("Root");
        Directory documents = new Directory("Documents");
        Directory pictures = new Directory("Pictures");
        FileNode readme = new FileNode("Readme.txt");
        FileNode image = new FileNode("image.jpg");
        root.add(documents);
        root.add(pictures);
        documents.add(readme);
        pictures.add(image);
        System.out.println("File structure:");
        root.display(0);
    }
}
相关推荐
步行cgn2 小时前
适配器设计模式:一个“翻译官”的故事
设计模式
扶尔魔ocy5 小时前
【QT C++】常用设计模式
c++·设计模式
她说..6 小时前
常见设计模式-观察者模式
java·spring boot·spring·观察者模式·设计模式
是2的10次方啊8 小时前
设计模式与生活⑨:一碗胡辣汤,用不着认识十几种香料
设计模式
geovindu1 天前
rust: Semaphore Pattern
开发语言·后端·设计模式·rust·代理模式·企业级信号量模式·同步型模式
是2的10次方啊1 天前
设计模式与生活⑧:快递到了,别一直刷物流
设计模式
raindayinrain2 天前
c++设计模式
开发语言·c++·设计模式
工一木子2 天前
设计模式与生活⑦:你打的车,隔着一个平台
设计模式
电子科技圈2 天前
2026 RISC-V中国峰会观察:编译调试工具链的“在场节奏”,释放了什么信号?
大数据·人工智能·设计模式·软件工程·软件构建·代码规范·risc-v
电子科技圈2 天前
Arm电机控制开发工具哪家强?
arm开发·单片机·嵌入式硬件·设计模式·软件构建