1. 程式人生 > >Java設定模式之:Composite組合模式

Java設定模式之:Composite組合模式

1,定義一個介面,作為組合的樞紐進行傳遞

package com.org.composite;
//定義介面:用來指定說明要完成那些行為動作
public interface Component {
    public void doSomething();  
}    
2,定義一個實現類,作為樹形結構的最低端,實際操作的也是該物件

package com.org.composite;
//實現Component介面,該類主要用來做一些業務邏輯或者其他動作的行為,實際儲存操作的也是該物件
public class Leaf implements Component{
    @Override
    public void doSomething() {
        System.out.println("Leaf doSomething");          
    }
}
3,定義另一個實現類,作為樹形結構的最頂端,作為組合模式中的實現者,裡面包含組合的增刪改查等操作方法,介面實現的方法作為兩個實現類的互通方法

package com.org.composite;
import java.util.ArrayList;
import java.util.List;
//實現Component介面,用來做物件Leaf的增刪改查,但這種方式是隱式的,實際操作的是Leaf。此時該物件可看作是Leaf,只不過不直接提供Leaf而是採用這種樹形結構方法來進行組合傳遞
public class Composite implements Component{
     List<Component> childs = new ArrayList<Component>();        
        public void add(Component child)  
        {  
            this.childs.add(child);  
        }        
        public void remove(Component child)  
        {  
            this.childs.remove(child);  
        }        
        public Component getChild(int i)  
        {  
            return this.childs.get(i);  
        }
    public void doSomething()  
    {  
        //這裡還包含迭代的思想,如果child是Leaf,則直接呼叫Leaf的doSomething方法,如果是Component的child,則此時的doSomething方法是Component
        //中的方法,相當於迭代迴圈
        for (Component child : childs)  
            child.doSomething();  
    }
}
4,開始測試

package com.org.composite;
public class Client {
    public static void main(String[] args)  
    {  
        /**
         *           composite1
         *           /      \
         *        leaf1   composite2
         *                  /   \
         *               leaf2  leaf3    
         *     Component為中間樞紐,將Leaf向上造型後利用Component來做操作,然後利用介面的特性即可操作Composite方法     
         *                
         * */  
        Component leaf1=new Leaf();  
        Component leaf2=new Leaf();  
        Component leaf3=new Leaf();  
        Composite composite1=new Composite();  
        Composite composite2=new Composite();           
        composite2.add(leaf2);  
        composite2.add(leaf3);  
        composite1.add(leaf1);  
        composite1.add(composite2);           
        composite1.doSomething();           
    }  
}