【设计模式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 小时前
别学23种了!Java项目中最常用的6个设计模式,附案例
java·后端·设计模式
Keya5 小时前
MacOS端口被占用的解决方法
前端·后端·设计模式
已读不回1436 小时前
设计模式-单例模式
前端·设计模式
long3161 天前
构建者设计模式 Builder
java·后端·学习·设计模式
一乐小哥1 天前
从 JDK 到 Spring,单例模式在源码中的实战用法
后端·设计模式
付春员1 天前
23种设计模式
设计模式
Zyy~2 天前
《设计模式》工厂方法模式
设计模式·工厂方法模式
ikkkkkkkl2 天前
C++设计模式:面向对象设计原则
c++·设计模式·面向对象
whitepure2 天前
万字详解Java中的面向对象(二)——设计模式
java·设计模式
稚辉君.MCA_P8_Java2 天前
豆包 Java的23种设计模式
java·linux·jvm·设计模式·kubernetes