【设计模式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("");
    }
}
相关推荐
烛阴2 小时前
【TS 设计模式完全指南】从零到一:掌握TypeScript建造者模式,让你的对象构建链式优雅
javascript·设计模式·typescript
yvya_4 小时前
常见设计模式详解
设计模式
至此流年莫相忘5 小时前
设计模式:模板方法模式
java·开发语言·设计模式
o0向阳而生0o10 小时前
100、23种设计模式之适配器模式(9/23)
设计模式·适配器模式
将编程培养成爱好12 小时前
C++ 设计模式《外卖菜单展示》
c++·设计模式
TechNomad20 小时前
设计模式:状态模式(State Pattern)
设计模式·状态模式
努力也学不会java20 小时前
【设计模式】 原型模式
java·设计模式·原型模式
TechNomad1 天前
设计模式:模板方法模式(Template Method Pattern)
设计模式·模板方法模式
leo03081 天前
7种流行Prompt设计模式详解:适用场景与最佳实践
设计模式·prompt
ytadpole1 天前
揭秘设计模式:工厂模式的五级进化之路
java·设计模式