Java设计模式之组合模式

COMPOSITE (Object Structural) 
Purpose 
Facilitates the creation of object hierarchies where each object 
can be treated independently or as a set of nested objects 
through the same interface. 
Use When 
1 Hierarchical representations of objects are needed.. 
2 Objects and compositions of objects should be treated uniformly. 
Example 
Sometimes the information displayed in a shopping cart is the 
product of a single item while other times it is an aggregation 
of multiple items. By implementing items as composites we can 
treat the aggregates and the items in the same way, allowing us 
to simply iterate over the tree and invoke functionality on each 
item. By calling the getCost() method on any given node we 
would get the cost of that item plus the cost of all child items, 
allowing items to be uniformly treated whether they were single 
items or groups of items. 

Java代码 
  1. package javaPattern.composite;  
  2.   
  3. import java.util.ArrayList;  
  4.   
  5.   
  6. interface Component{  
  7.     public void operation();  
  8. }  
  9. public class Composite implements Component{  
  10.     private ArrayList<Component> al = new ArrayList<Component>();  
  11.     @Override  
  12.     public void operation() {  
  13.         System.out.println("Composite's operation...");  
  14.           
  15.     }  
  16.     public void add(Component c){  
  17.         al.add(c);  
  18.     }  
  19.     public void remove(Component c){  
  20.         al.remove(c);  
  21.     }  
  22.     public Component getChild(int index){  
  23.         return al.get(index);  
  24.     }  
  25. }  
  26. class Leaf implements Component{  
  27.   
  28.     @Override  
  29.     public void operation() {  
  30.         System.out.println("leaf's operation..");  
  31.           
  32.     }  
  33.       
  34. }  
  35. class Client{  
  36.     public static void main(String[] args) {  
  37.         Composite composite = new Composite();  
  38.         Component component1 = new Leaf();  
  39.         Component component2 = new Leaf();  
  40.         composite.add(component1);  
  41.         composite.add(component2);  
  42.     }  
  43. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值