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

來源:互聯網
上載者:User

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(int index) {        try {            return mChildren[index];        } catch (IndexOutOfBoundsException ex) {            return null;        }    }    //other methods}

4.效果
(1).結構型模式
(2).定義了包含基本對象和組合對象的類階層。這種結構能夠靈活控制基本對象與組合對象的使用。
(3).簡化客戶代碼。基本對象和組合對象有一致性,使用者不用區分它們。
(4).使得更容易添加新類型的組件。
(5).使你的設計變得更加一般化。
 

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.