组合模式-树状结构

 1 public class TreeStructures {
 2 
 3     public static void main(String[] args) {
 4         //创建树
 5         Composite root = new Composite("树根");
 6         root.Add(new Leaf("叶子A"));
 7         root.Add(new Leaf("叶子B"));
 8         //节点X及子节点
 9         Composite composite1 = new Composite("节点X");
10         composite1.Add(new Leaf("叶子XA"));
11         composite1.Add(new Leaf("叶子XB"));
12         //节点Y及子节点
13         Composite composite2 = new Composite("节点Y");
14         composite2.Add(new Leaf("叶子YA"));
15         composite2.Add(new Leaf("叶子YB"));
16         //节点拼接
17         composite1.Add(composite2);
18         root.Add(composite1);
19         //显示树状结构
20         root.Show(1);
21     }
22 }
23 //树中分支节点与叶子节点的抽象父类
24 abstract class Component{
25     //组件名称
26     protected String componentName;
27     
28     public Component(String componentName) {
29         this.componentName = componentName;
30     }
31     //增加分支/叶子节点的方法
32     public abstract void Add(Component component);
33     //移除分支/叶子节点的方法
34     public abstract void Remove(Component component);
35     //按照深度显示树状结构的方法
36     public abstract void Show(int depth);
37 }
38 class Composite extends Component{
39 
40     //分支节点集合
41     private List<Component> childrenList = new ArrayList<Component>();
42     public Composite(String componentName) {
43         super(componentName);
44     }
45 
46     //增加子节点
47     @Override
48     public void Add(Component component) {
49         childrenList.add(component);
50     }
51 
52     //删除子节点
53     @Override
54     public void Remove(Component component) {
55         childrenList.remove(component);
56     }
57 
58     //显示子节点
59     @Override
60     public void Show(int depth) {
61         for(int i=0;i<depth;i++) {
62             System.out.print('+');
63         }
64         System.out.print(componentName+'\n');
65         for(int i=0;i<childrenList.size();i++) {
66             childrenList.get(i).Show(depth+2);
67         }
68     }
69     
70 }
71 //树叶节点类
72 class Leaf extends Component{
73 
74     public Leaf(String componentName) {
75         super(componentName);
76     }
77 
78     //增加子节点
79     @Override
80     public void Add(Component component) {
81         System.out.println("叶子节点无法添加子节点");
82     }
83 
84     //移除子节点
85     @Override
86     public void Remove(Component component) {
87         System.out.println("叶子节点无法删除节点");
88     }
89 
90     @Override
91     public void Show(int depth) {
92         for(int i=0;i<depth;i++) {
93             System.out.print('+');
94         }
95         System.out.print(componentName+'\n');
96     }
97     
98 }

输出:

posted @ 2017-11-23 10:12  勤劳的杯子  阅读(188)  评论(0编辑  收藏  举报