【设计模式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("");
    }
}
相关推荐
永卿0016 小时前
设计模式-迭代器模式
java·设计模式·迭代器模式
使二颗心免于哀伤6 小时前
《设计模式之禅》笔记摘录 - 10.装饰模式
笔记·设计模式
Amagi.10 小时前
Java设计模式-建造者模式
java·设计模式·建造者模式
源代码•宸1 天前
深入浅出设计模式——创建型模式之工厂模式
设计模式
天天进步20151 天前
设计模式在Java中的实际应用:单例、工厂与观察者模式详解
java·观察者模式·设计模式
尘似鹤1 天前
c++注意点(12)----设计模式(生成器)
c++·设计模式
归云鹤1 天前
设计模式十:单件模式 (Singleton Pattern)
单例模式·设计模式
夜影风1 天前
23种常用设计模式介绍
设计模式
YoseZang1 天前
【设计模式】GoF设计模式之代理模式(Proxy Pattern)
设计模式·代理模式
hqxstudying2 天前
J2EE模式---业务代表模式
java·前端·python·设计模式·java-ee·mvc