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. }  

你可能感兴趣的:(java,设计模式,C++,c,C#)