天天看點

Android設計模式系列(1)--SDK源碼之組合模式

原文連結: http://www.cnblogs.com/qianxudetianxia/archive/2011/07/29/2121488.html

Android中對組合模式的應用,可謂是泛濫成粥,随處可見,那就是View和ViewGroup類的使用。在android UI設計,幾乎所有的widget和布局類都依靠這兩個類。

組合模式,Composite Pattern,是一個非常巧妙的模式。幾乎所有的面向對象系統都應用到了組合模式。

1.意圖

将對象View和ViewGroup組合成樹形結構以表示"部分-整體"的層次結構(View可以做為ViewGroup的一部分)。

組合模式使得使用者對單個對象View群組合對象ViewGroup的使用具有一緻性。

熱點詞彙: 部分-整體 容器-内容 樹形結構 一緻性 葉子 合成 安全性 透明性

2.結構

針對View和ViewGroup的實際情況,我們選擇安全式的組合模式(在組合對象中添加add,remove,getChild方法),添加少許的注釋,我們把上圖修改為:

3.代碼

View類的實作:

public class View{
        //... ...
        //省略了無關的方法
}      

ViewGroup的實作:

public abstract class ViewGroup extends View{
    /**
     * Adds a child view. 
     */
    public void addView(View child) {
        //...
    }
 
    public void removeView(View view) {
        //...
    }
 
    /**
     * Returns the view at the specified position in the group.
     */
    public View getChildAt(intindex) {
        try{
            returnmChildren[index];
        }catch(IndexOutOfBoundsException ex) {
            returnnull;
        }
    }
 
    //other methods
}      

(1).結構型模式

(2).定義了包含基本對象群組合對象的類層次結構。這種結構能夠靈活控制基本對象與組合對象的使用。

(3).簡化客戶代碼。基本對象群組合對象有一緻性,使用者不用區分它們。

(4).使得更容易添加新類型的元件。

(5).使你的設計變得更加一般化。