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).使你的設計變得更加一般化。