自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Android設(shè)計(jì)模式系列-組合模式

移動(dòng)開發(fā) Android
Android中對(duì)組合模式的應(yīng)用,可謂是泛濫成粥,隨處可見,那就是View和ViewGroup類的使用。在android UI設(shè)計(jì),幾乎所有的widget和布局類都依靠這兩個(gè)類。

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):

  1. public class View{ 
  2.  
  3.         //... ... 
  4.  
  5.        //省略了無(wú)關(guān)的方法 
  6.  

ViewGroup的實(shí)現(xiàn):

  1. public abstract class ViewGroup extends View{ 
  2.  
  3.     /** 
  4.    * Adds a child view.  
  5.  
  6.     */ 
  7.  
  8.    public void addView(View child) { 
  9.  
  10.        //... 
  11.  
  12.     } 
  13.  
  14.  
  15.  
  16.    public void removeView(View view) { 
  17.  
  18.         //... 
  19.  
  20.     } 
  21.  
  22.  
  23.  
  24.    /** 
  25.  
  26.      * Returns the view at the specified position in the group. 
  27.  
  28.     */ 
  29.  
  30.     public View getChildAt(int index) { 
  31.  
  32.        try { 
  33.  
  34.            return mChildren[index]; 
  35.  
  36.       } catch (IndexOutOfBoundsException ex) { 
  37.  
  38.            return null; 
  39.  
  40.       } 
  41.  
  42.    } 
  43.  
  44.  
  45.  
  46.     //other methods 
  47.  

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ì)變得更加一般化。

責(zé)任編輯:張葉青 來源: eoe Android開發(fā)者社區(qū)
相關(guān)推薦

2013-11-26 16:20:26

Android設(shè)計(jì)模式

2013-11-26 17:00:08

Android設(shè)計(jì)模式

2013-11-26 17:15:13

Android設(shè)計(jì)模式

2013-11-26 17:09:57

Android設(shè)計(jì)模式

2013-11-26 16:29:22

Android設(shè)計(jì)模式

2013-11-26 16:39:21

Android設(shè)計(jì)模式

2022-01-12 13:33:25

工廠模式設(shè)計(jì)

2020-10-23 09:40:26

設(shè)計(jì)模式

2020-11-03 13:05:18

命令模式

2020-11-04 08:54:54

狀態(tài)模式

2021-09-16 06:44:05

組合模式設(shè)計(jì)

2021-06-09 08:53:34

設(shè)計(jì)模式策略模式工廠模式

2020-10-19 09:28:00

抽象工廠模式

2021-09-29 13:53:17

抽象工廠模式

2022-01-14 09:22:22

設(shè)計(jì)模式橋接

2021-03-02 08:50:31

設(shè)計(jì)單例模式

2020-10-21 14:29:15

原型模式

2020-11-09 08:20:33

解釋器模式

2020-10-20 13:33:00

建造者模式

2012-01-13 15:59:07

點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)