public abstract class Component {
2
3 protected String name;
4
5 public Component(String name) {
6 this.name = name;
7 }
8
9 //获取分支下的所有叶子构件和树枝构件
10 public abstract void display(int depth);
11
12 }
public class Composite extends Component {
2
3 public Composite(String name) {
4 super(name);
5 }
6
7 //构建容器
8 private ArrayList componentArrayList = new ArrayList();
9
10 //增加一个叶子构件或树枝构件
11 public void add(Component component) {
12 this.componentArrayList.add(component);
13 }
14
15 //删除一个叶子构件或树枝构件
16 public void remove(Component component) {
17 this.componentArrayList.remove(component);
18 }
19
20 @Override
21 public void display(int depth) {
22 //输出树形结构
23 for(int i=0; i<depth; i++) {
24 System.out.print(’-’);
25 }
26 System.out.println(name);
27
28 //下级遍历
29 for (Component component : componentArrayList) {
30 component.display(depth + 1);
31 }
32 }
33
34 }
public class Leaf extends Component {
2
3 public Leaf(String name) {
4 super(name);
5 }
6
7 @Override
8 public void display(int depth) {
9 //输出树形结构的叶子节点
10 for(int i=0; i<depth; i++) {
11 System.out.print(’-’);
12 }
13 System.out.println(name);
14 }
15
16 }