【设计模式09】组合模式

前言

适用于树形结构,如公司的组织架构,目录和文件夹

UML类图

代码示例

java 复制代码
package com.sw.learn.pattern.C_structre.c_composite;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

// 抽象组件
interface FileSystemComponent {
    void display(String indent);
}

// 叶子节点
class File implements FileSystemComponent {
    private String name;

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

    public void display(String indent) {
        System.out.println(indent + "- File: " + name);
    }
}

// 容器节点
class Directory implements FileSystemComponent {
    private String name;
    private List<FileSystemComponent> children = new ArrayList<>();

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

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

    public void display(String indent) {
        System.out.println(indent + "+ Directory: " + name);
        for (FileSystemComponent c : children) {
            c.display(indent + "  ");
        }
    }
}

// 使用示例
public class Main {
    public static void main(String[] args) {
        Directory root = new Directory("root");
        root.add(new File("file1.txt"));
        root.add(new File("file2.txt"));

        Directory subDir = new Directory("sub");
        subDir.add(new File("file3.txt"));

        root.add(subDir);

        root.display("");
    }
}
相关推荐
Tiny_React10 小时前
智能体设计模式-附录 C - 智能体框架快速概览
设计模式
YBN娜13 小时前
设计模式-创建型设计模式
java·开发语言·设计模式
YuanlongWang14 小时前
C# 设计模式——单例模式
单例模式·设计模式·c#
Code_Geo14 小时前
agent设计模式:第二章节—路由
网络·设计模式·路由
太过平凡的小蚂蚁15 小时前
解耦的艺术:深入理解设计模式之命令模式
设计模式·命令模式
Meteors.17 小时前
23种设计模式——外观模式(Facade Pattern)详解
设计模式·外观模式
胖虎117 小时前
iOS中的设计模式(九)- 外观模式 用外观模式点一份外卖:Swift 实战讲解
设计模式·外观模式
Asort19 小时前
JavaScript设计模式(十六)——迭代器模式:优雅遍历数据的艺术
前端·javascript·设计模式
昨天的猫19 小时前
原来我们写的单例还存在缺陷~~
设计模式
Tiny_React19 小时前
智能体设计模式-CH13:人类参与环节(Human-in-the-Loop)
设计模式