9/6
软件设计 石家庄铁道大学信息学院
实验10:组合模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解组合模式的动机,掌握该模式的结构;
2、能够利用组合模式解决实际问题。
[实验任务一]:组合模式
用透明组合模式实现教材中的“文件夹浏览”这个例子。
实验要求:
1.文件的执行不需真正实现,只需简单提示即可;
2.提交源代码;
public abstract class Component {
protected String name;
public Component(String name) {
this.name = name;
}
public abstract void add(Component component);
public abstract void remove(Component component);
public abstract void display(int depth);
}
public class Leaf extends Component {
public Leaf(String name) {
super(name);
}
@Override
public void add(Component component) {
System.out.println(name + " 不能添加子节点");
}
@Override
public void remove(Component component) {
System.out.println(name + " 不能移除子节点");
}
@Override
public void display(int depth) {
System.out.println("-".repeat(depth) + name);
}
}
import java.util.ArrayList;
import java.util.List;
public class Composite extends Component {
private List<Component> children = new ArrayList<>();
public Composite(String name) {
super(name);
}
@Override
public void add(Component component) {
children.add(component);
}
@Override
public void remove(Component component) {
children.remove(component);
}
@Override
public void display(int depth) {
System.out.println("-".repeat(depth) + name + ":");
for (Component component : children) {
component.display(depth + 2);
}
}
}
public class Client {
public static void main(String[] args) {
Component root = new Composite("root");
Component dir1 = new Composite("dir1");
Component dir2 = new Composite("dir2");
Component file1 = new Leaf("file1");
Component file2 = new Leaf("file2");
root.add(dir1);
root.add(dir2);
dir1.add(file1);
dir2.add(file2);
root.display(1);
}
}
3.注意编程规范。

浙公网安备 33010602011771号