软件设计-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又包含文件 } }