首页 > 代码库 > 跟着ZHONGHuan学习设计模式--组合模式

跟着ZHONGHuan学习设计模式--组合模式

跟着ZHONGHuan学习设计模式

组合模式

介绍:

         想必你已经了解了数据结构中的树,ok,组合模式对于你就是一会儿的功夫了。组合模式相对来说比较简单。看一下定义

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

        

         暂时没有想到好的例子,如果你有,请告诉我。下面我用树来对组合模式进行解释。树的结构是下面的这样的:

        

         没棵树有一个根节点,也有叶子节点和树枝节点,一些结构都是用树结构表示的,例如树形菜单,文件和文件夹目录。那么如何存储管理这样的树结构,可以组合模式来解决。

 

组合模式的类图

        

         组合模式比较简单,所以,通过下面的代码,应该就能了解组合模式的含义了。

 

[java] view plaincopy
  1. import java.util.ArrayList;  
  2.   
  3. abstract class Component  
  4. {  
  5.     protected String name; //这个用来标示一下节点  
  6.     public Component(String name)  
  7.     {  
  8.         this.name = name;  
  9.     }  
  10.    
  11.     public abstract void add(Component c);//增加儿子节点  
  12.     public abstract void remove(Component c);//删除儿子节点  
  13. }  
  14.   
  15. class Leaf extends Component  
  16. {  
  17.     public Leaf(String name)  
  18.     {  
  19.        super(name);  
  20.     }  
  21.    
  22.     public  void add(Component c)  
  23.     {  
  24.        System.out.println("叶子节点不能增加子节点");  
  25.     }  
  26.    
  27.     public void remove(Component c)  
  28.     {  
  29.         System.out.println("叶子节点没有子节点,移除神马");  
  30.     }  
  31. }  
  32.   
  33. class Composite extends Component  
  34. {  
  35.    
  36.     ArrayList<Component> child;  
  37.    
  38.     public Composite(String name)  
  39.     {  
  40.         super(name);  
  41.         if (child == null)  
  42.         {  
  43.             child = new ArrayList<Component>();  
  44.         }  
  45.     }  
  46.    
  47.     public void add(Component c)  
  48.     {  
  49.         this.child.add(c);  
  50.     }  
  51.    
  52.     public void remove(Component c)  
  53.     {  
  54.         this.child.remove(c);  
  55.     }  
  56. }  
  57.   
  58. public class Client{  
  59.     public static void main(String[] args)  
  60.     {  
  61.         Component tree=new Composite("A");//根节点一般是composite节点,给根节点取名A  
  62.         Component leafB=new Leaf("B");//创建了一个叶子节点B  
  63.         tree.add(leafB);//根节点有一个叶子节点儿子  
  64.           
  65.         Component branchC=new Composite("C");//一个树枝节点C  
  66.         tree.add(branchC);//树枝节点C是根节点A的子节点  
  67.           
  68.         Component leafD = new Leaf("D");  
  69.         branchC.add(leafD);//树枝节点C有一个叶子子节点D  
  70.           
  71.         //树结构大致构造完毕  
  72.     }  
  73. }  


         组合模式让我们能用树形方式创建对象的结构,树里面包含了组合以及个别的对象。使用组合结构,我们能把相同的操作应用在组合和个别对象上,换句话说,在大多数情况下,我们可以忽略对象组合和个别对象之间的差别。