【设计模式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("");
    }
}
相关推荐
zzu123zsw19 小时前
业务拆分后的治理深水区:解构企业级微服务六大核心设计模式与高可用落真实践
微服务·设计模式·架构·高可用·微服务架构设计
牧瀬クリスだ19 小时前
观察者模式:一个对象变化,一群对象自动响应
java·观察者模式·设计模式
拆房老料1 天前
【第四部分:Agentic 智能体设计模式】16. 一个 Prompt 搞不定复杂任务?试试 Prompt Chaining
java·前端·人工智能·设计模式·prompt
MobotStone1 天前
AI 写代码越来越爽,但程序员可能越来越废了
人工智能·设计模式
墨子夕1 天前
设计模式——Java × Python 双语言精讲 · 23 个经典模式 + 现代演进(前言篇)
java·开发语言·设计模式
墨子夕2 天前
设计模式——Java × Python 双语言精讲 · 23 个经典模式 + 现代演进(第一篇)
java·python·设计模式
General_G2 天前
创建型模式—原型(Prototype)模式
c++·设计模式·原型模式
geovindu2 天前
rust: Template Method Pattern
开发语言·后端·设计模式·rust·行为模式·模板方法模
geovindu2 天前
rust: Template Method Pattern(续)
开发语言·后端·设计模式·rust·行为模式·板方法模式
博风2 天前
17、设计模式应用举例:单件模式:多线程争冠军
设计模式