菜鸟的博客

纵有疾风起,人生不言弃。

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

软件设计-Tutorial10

[实验任务一]:组合模式

用透明组合模式实现教材中的“文件夹浏览”这个例子。

复制代码
package Tutorial10;

abstract  class FileSystemComponent {
    public void add(FileSystemComponent component) {
        throw new UnsupportedOperationException();
    }

    public void remove(FileSystemComponent component) {
        throw new UnsupportedOperationException();
    }

    public FileSystemComponent getChild(int index) {
        throw new UnsupportedOperationException();
    }

    public abstract void execute();  // 执行方法,打印提示信息
}
复制代码
复制代码
package Tutorial10;
public class File extends FileSystemComponent{
    private String name;
    public File(String name) {
        this.name = name;
    }
    @Override
    public void execute() {
        System.out.println("执行文件:" + name);  // 模拟文件的执行
    }
}
复制代码
复制代码
package Tutorial10;
import java.util.ArrayList;
import java.util.List;

public class Folder extends FileSystemComponent{
    private String name;
    private List<FileSystemComponent> components = new ArrayList<>();

    public Folder(String name) {
        this.name = name;
    }
    @Override
    public void add(FileSystemComponent component) {
        components.add(component);
    }
    @Override
    public void remove(FileSystemComponent component) {
        components.remove(component);
    }
    @Override
    public FileSystemComponent getChild(int index) {
        return components.get(index);
    }
    @Override
    public void execute() {
        System.out.println("执行文件夹:" + name);
        for (FileSystemComponent component : components) {
            component.execute();  // 执行文件夹中的每个文件或子文件夹
        }
    }
}
复制代码
复制代码
package Tutorial10;

public class FileSystemTest {
    public static void main(String[] args) {
        // 创建文件
        File file1 = new File("文件1.txt");
        File file2 = new File("文件2.txt");

        // 创建文件夹
        Folder folder1 = new Folder("文件夹1");
        Folder folder2 = new Folder("文件夹2");

        // 将文件添加到文件夹
        folder1.add(file1);
        folder1.add(file2);

        // 将文件夹添加到另一个文件夹
        folder2.add(folder1);

        // 执行文件夹操作,展示透明组合模式
        folder2.execute();  // 执行文件夹2,里面包含文件夹1,文件夹1又包含文件
    }
}
复制代码

 

posted on   hhmzd233  阅读(4)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2023-11-06 3.增删改查的实现(1)
点击右上角即可分享
微信分享提示