【设计模式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("");
    }
}
相关推荐
Poetinthedusk11 小时前
设计模式-命令模式
windows·设计模式·c#·wpf·命令模式
雨中飘荡的记忆12 小时前
设计模式之桥接模式:从原理到实战
设计模式
北海屿鹿12 小时前
设计模式概述
设计模式
真夜14 小时前
发布观察者模式使用场景记录
设计模式
会员果汁16 小时前
4.设计模式-代理模式
设计模式·代理模式
有一个好名字17 小时前
设计模式-代理模式
java·设计模式·代理模式
catchadmin18 小时前
PHP 之高级面向对象编程 深入理解设计模式、原则与性能优化
设计模式·性能优化·php
郝学胜-神的一滴18 小时前
使用EBO绘制图形:解锁高效渲染与内存节省之道
c++·qt·游戏·设计模式·系统架构·图形渲染
冷崖19 小时前
原型模式-创建型
设计模式·原型模式
Poetinthedusk19 小时前
设计模式-单例模式
单例模式·设计模式