【设计模式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("");
    }
}
相关推荐
N_NAN_N3 小时前
类图+案例+代码详解:软件设计模式----原型模式
java·设计模式·原型模式
摘星编程4 小时前
组合模式在SSO搜索和关键词重叠法中的优化应用
组合模式·搜索算法·sso搜索优化·关键词检索·技术架构设计
缘来是庄4 小时前
设计模式之组合模式
java·设计模式·组合模式
DKPT4 小时前
Java组合模式实现方式与测试方法
java·笔记·学习·设计模式·组合模式
N_NAN_N7 小时前
类图+案例+代码详解:软件设计模式----单例模式
java·单例模式·设计模式
尤物程序猿7 小时前
设计模式之代理模式--数据库查询代理和调用日志记录
设计模式·代理模式
GodKeyNet16 小时前
设计模式-模板模式
设计模式·模板模式
缘来是庄20 小时前
设计模式之建造者模式
java·设计模式·建造者模式
铛铛啦啦啦1 天前
“对象创建”模式之原型模式
设计模式·原型模式