合成模式将对象组织到树结构中,可以用来描述整体与部分的关系。合成模式可以使客户端将单纯元素与复合元素同等看待。

合成模式:安全式和透明式合成模式

 

1,安全式合成模式


抽象构件角色:这是一个抽象角色,它给参加组合的对象规定一个接口

树叶构件角色:代表参加组合的树叶对象,一个树叶没有下级的子对象,定义参加组合的原始对象的行为

树枝构件角色:代表参加组合的有子对象的对象,并给出树枝构件对象的行为

1.           package javaPattern.composite;  

2.             

3.           import java.util.ArrayList;  

4.             

5.             

6.           interface Component{  

7.               public void operation();  

}  

8.           public class Composite implements Component{  

9.               private ArrayList<Component> al = new ArrayList<Component>();  

10.          public void operation() {  

11.              System.out.println("Composite's operation...");  

12.                

13.          }  

  }

14.          public void add(Component c){  

15.              al.add(c);  

16.          }  

17.          public void remove(Component c){  

18.              al.remove(c);  

19.          }  

20.          public Component getChild(int index){  

21.              return al.get(index);  

22.          }  

23.      }  

24.      class Leaf implements Component{  

25.        

26.          @Override  

27.          public void operation() {  

28.              System.out.println("leaf's operation..");  

29.                

30.          }  

31.      }  

32.      class Client{  

33.          public static void main(String[] args) {  

34.              Composite composite = new Composite();  

35.              Component component1 = new Leaf();  

36.              Component component2 = new Leaf();  

37.              composite.add(component1);  

38.              composite.add(component2);  

39.          }  

40.      }  

 

2,透明式合成模式

透明式合成模式是在抽象组件角色中声明对对象的操作

posted on 2011-01-13 10:47  魔战  阅读(231)  评论(0编辑  收藏  举报