完成设计模式实验:
实验10:组合模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解组合模式的动机,掌握该模式的结构;
2、能够利用组合模式解决实际问题。
[实验任务一]:组合模式
用透明组合模式实现教材中的“文件夹浏览”这个例子。
实验要求:
1. 文件的执行不需真正实现,只需简单提示即可;
2. 提交源代码;
- package define;
import java.util.ArrayList;
import java.util.List;
// 抽象组件
interface Component {
void add(Component component);
void remove(Component component);
Component getChild(int i);
void operation();
}
// 叶子组件
class File implements Component {
private String name;
public File(String name) {
this.name = name;
}
@Override
public void add(Component component) {
System.out.println(name + "不能添加子节点");
}
@Override
public void remove(Component component) {
System.out.println(name + "不能移除子节点");
}
@Override
public Component getChild(int i) {
System.out.println(name + "没有子节点");
return null;
}
@Override
public void operation() {
System.out.println("文件名:" + name);
}
}
// 组合组件
class Folder implements Component {
private String name;
private List<Component> children;
public Folder(String name) {
this.name = name;
this.children = new ArrayList<>();
}
@Override
public void add(Component component) {
children.add(component);
}
@Override
public void remove(Component component) {
children.remove(component);
}
@Override
public Component getChild(int i) {
return children.get(i);
}
@Override
public void operation() {
System.out.println("文件夹名:" + name);
for (Component component : children) {
component.operation();
}
}
}
// 客户端代码
public class CompositePatternDemo {
public static void main(String[] args) {
Folder rootFolder = new Folder("根目录");
Folder mathFolder = new Folder("数学");
Folder physicsFolder = new Folder("物理");
Folder chineseFolder = new Folder("语文");
File mathFile1 = new File("math1.txt");
File mathFile2 = new File("math2.txt");
rootFolder.add(mathFolder);
rootFolder.add(physicsFolder);
rootFolder.add(chineseFolder);
mathFolder.add(mathFile1);
mathFolder.add(mathFile2);
// 执行文件操作
rootFolder.operation();
}
}
3.注意编程规范。
标签:name,10.31,日报,component,void,Component,Folder,public From: https://www.cnblogs.com/lijianlongCode13/p/18571777