1 package com.tn.pattern;
2
3 import java.util.Vector;
4
5 public class Client {
6 public static void main(String[] args) {
7 Component china=new Composite("中国");
8
9 Component jiangsu=new Composite("江苏");
10 Component anhui=new Composite("安徽");
11
12 Component nanjing=new Leaf("南京");
13 Component suzhou=new Leaf("苏州");
14
15 Component hefei=new Leaf("合肥");
16 Component wuhu=new Leaf("芜湖");
17 Component maanshan=new Leaf("马鞍山");
18
19 Component beijing=new Leaf("北京");
20 Component shanghai=new Leaf("上海");
21 Component tianjing=new Leaf("天津");
22 Component chongqing=new Leaf("重庆");
23
24 china.add(beijing);
25 china.add(shanghai);
26 china.add(tianjing);
27 china.add(chongqing);
28 china.add(jiangsu);
29 china.add(anhui);
30 jiangsu.add(nanjing);
31 jiangsu.add(suzhou);
32 anhui.add(hefei);
33 anhui.add(wuhu);
34 anhui.add(maanshan);
35
36 china.getChild();
37 System.out.println("---------------------------");
38 jiangsu.getChild();
39 System.out.println("---------------------------");
40 anhui.getChild();
41 System.out.println("---------------------------");
42 beijing.doSth();
43 shanghai.doSth();
44 tianjing.doSth();
45 chongqing.doSth();
46 System.out.println("---------------------------");
47 nanjing.doSth();
48 suzhou.doSth();
49 System.out.println("---------------------------");
50 hefei.doSth();
51 wuhu.doSth();
52 maanshan.doSth();
53 }
54 }
55
56 interface Component{
57 void doSth();
58 void add(Component component);
59 void getChild();
60 }
61
62 class Leaf implements Component{
63 private String name;
64 public Leaf(String name){
65 this.name=name;
66 }
67 @Override
68 public void doSth() {
69 System.out.println(name+" Leaf doSth()");
70 }
71 public void add(Component component){}
72 public void getChild(){}
73 }
74
75 class Composite implements Component{
76 private String name;
77 public Composite(String name){
78 this.name=name;
79 }
80 private Vector<Component> components=new Vector<Component>();
81 @Override
82 public void doSth() {
83 System.out.println(name+" Composite doSth()");
84 }
85 public void add(Component component){
86 components.addElement(component);
87 }
88 public void remove(Component componet){
89 components.removeElement(componet);
90 }
91 public void getChild(){
92 for(Component component:components){
93 if(component instanceof Leaf){
94 component.doSth();
95 }else{
96 component.doSth();
97 component.getChild();
98 }
99 }
100 }
101 }