《JAVA与模式》之组合模式

定义(GoF《设计模式》):

     将对象组合成树形结构以表示“部分整体”的层次结构。组合模式使得用户对单个对象和使用具有一致性。

及角色:
  1.Component 是组合中的对象声明接口,在适当的情况下,实现所有类共有接口的默认行为。声明一个接口用于访问和管理Component
子部件。
  2.Leaf 在组合中表示叶子结点对象,叶子结点没有子结点。
  3.Composite 定义有枝节点行为,用来存储子部件,在Component接口中实现与子部件有关操作,如增加(add)和删除

(remove)等。


 1 public static void main(String[] args) {
 2         
 3         Component component=new Composite("根节点");
 4         Component child=new Composite("一级子节点child");
 5         Component child_1=new Leaf("一级子节点child之子节点一");
 6         Component child_2=new Leaf("一级子节点child之子节点二");
 7         child.add(child_1);
 8         child.add(child_2);
 9         Component child2=new Composite("一级子节点child2");
10         component.add(child);
11         component.add(child2);
12         component.foreach();
13     }
14 
15 }
16  abstract class Component {  
17      
18      String name;
19      
20      public Component(String s){
21          
22          this.name=s;
23      }
24      public abstract void add(Component c);
25      public abstract void remove(Component c);
26      public abstract void foreach();
27  }
28 //组合类
29  class Composite extends Component{
30     private List<Component>child=new ArrayList<Component>
31     ();
32      
33     public Composite(String s) {
34         super(s);
35         // TODO Auto-generated constructor stub
36     }
37 
38     @Override
39     public void add(Component c) {
40         child.add(c);
41         
42     }
43 
44     @Override
45     public void foreach() {
46         // TODO Auto-generated method stub
47         System.out.println("节点名:	"+name);
48         for (Component c : child) {
49             c.foreach();
50         }
51     }
52 
53     @Override
54     public void remove(Component c) {
55         // TODO Auto-generated method stub
56         child.remove(c);
57     }
58      
59  }
60  //不在有根节点
61  class Leaf extends Component{
62 
63     public Leaf(String s) {
64         super(s);
65         
66     }
67 
68     @Override
69     public void add(Component c) {
70         // TODO Auto-generated method stub
71         
72     }
73     @Override
74     public void foreach() {
75         System.out.println("tself name-->"+this.name);
76     }
77 
78     @Override
79     public void remove(Component c) {
80         // TODO Auto-generated method stub
81         
82     }
83      
84  }

执行结果:

节点名: 根节点
节点名: 一级子节点child
tself name-->一级子节点child之子节点一
tself name-->一级子节点child之子节点二
节点名: 一级子节点child2


什么情况下使用组合模式

       引用大话设计模式的片段:“当发现需求中是体现部分与整体层次结构时,以及你希望用户可以忽略组合对象与单个对象的不同,统一地使用组合结构中的所有对象时,就应该考虑组合模式了。”

参考地址:

http://blog.csdn.net/jason0539/article/details/22642281

http://blog.csdn.net/guolin_blog/article/details/9153753

http://www.2cto.com/kf/201206/137680.html

原文地址:https://www.cnblogs.com/draem0507/p/3794844.html