Android設(shè)計(jì)模式系列-組合模式
Android中對(duì)組合模式的應(yīng)用,可謂是泛濫成粥,隨處可見,那就是View和ViewGroup類的使用。在android  UI設(shè)計(jì),幾乎所有的widget和布局類都依靠這兩個(gè)類。
組合模式,Composite  Pattern,是一個(gè)非常巧妙的模式。幾乎所有的面向?qū)ο笙到y(tǒng)都應(yīng)用到了組合模式。
1.意圖
將對(duì)象View和ViewGroup組合成樹形結(jié)構(gòu)以表示"部分-整體"的層次結(jié)構(gòu)(View可以做為ViewGroup的一部分)。
組合模式使得用戶對(duì)單個(gè)對(duì)象View和組合對(duì)象ViewGroup的使用具有一致性。
熱點(diǎn)詞匯:  部分-整體 容器-內(nèi)容 樹形結(jié)構(gòu) 一致性 葉子 合成 安全性  透明性
2.結(jié)構(gòu)

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

3.代碼
View類的實(shí)現(xiàn):
- public class View{
 - //... ...
 - //省略了無關(guān)的方法
 - }
 
ViewGroup的實(shí)現(xiàn):
- 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).結(jié)構(gòu)型模式
(2).定義了包含基本對(duì)象和組合對(duì)象的類層次結(jié)構(gòu)。這種結(jié)構(gòu)能夠靈活控制基本對(duì)象與組合對(duì)象的使用。
(3).簡(jiǎn)化客戶代碼。基本對(duì)象和組合對(duì)象有一致性,用戶不用區(qū)分它們。
(4).使得更容易添加新類型的組件。
(5).使你的設(shè)計(jì)變得更加一般化。















 
 
 








 
 
 
 