Android设计模式系列-组合模式

移动开发 Android
Android中对组合模式的应用,可谓是泛滥成粥,随处可见,那就是View和ViewGroup类的使用。在android UI设计,几乎所有的widget和布局类都依靠这两个类。

Android中对组合模式的应用,可谓是泛滥成粥,随处可见,那就是View和ViewGroup类的使用。在android UI设计,几乎所有的widget和布局类都依靠这两个类。
组合模式,Composite Pattern,是一个非常巧妙的模式。几乎所有的面向对象系统都应用到了组合模式。

1.意图
将对象View和ViewGroup组合成树形结构以表示"部分-整体"的层次结构(View可以做为ViewGroup的一部分)。
组合模式使得用户对单个对象View和组合对象ViewGroup的使用具有一致性。
热点词汇: 部分-整体 容器-内容 树形结构 一致性 叶子 合成 安全性 透明性

2.结构

针对View和ViewGroup的实际情况,我们选择安全式的组合模式(在组合对象中添加add,remove,getChild方法),添加少许的注释,我们把上图修改为:

3.代码
View类的实现:

  1. public class View{ 
  2.  
  3.         //... ... 
  4.  
  5.        //省略了无关的方法 
  6.  

ViewGroup的实现:

  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).结构型模式
(2).定义了包含基本对象和组合对象的类层次结构。这种结构能够灵活控制基本对象与组合对象的使用。
(3).简化客户代码。基本对象和组合对象有一致性,用户不用区分它们。
(4).使得更容易添加新类型的组件。
(5).使你的设计变得更加一般化。

责任编辑:张叶青 来源: eoe Android开发者社区
相关推荐

2013-11-26 16:20:26

Android设计模式

2013-11-26 17:15:13

Android设计模式

2013-11-26 17:00:08

Android设计模式

2013-11-26 17:09:57

Android设计模式

2013-11-26 16:39:21

Android设计模式

2013-11-26 16:29:22

Android设计模式

2022-01-12 13:33:25

工厂模式设计

2021-09-16 06:44:05

组合模式设计

2020-10-23 09:40:26

设计模式

2020-11-03 13:05:18

命令模式

2020-11-04 08:54:54

状态模式

2021-09-29 13:53:17

抽象工厂模式

2021-03-02 08:50:31

设计单例模式

2020-10-21 14:29:15

原型模式

2022-01-14 09:22:22

设计模式桥接

2020-10-19 09:28:00

抽象工厂模式

2021-06-09 08:53:34

设计模式策略模式工厂模式

2021-10-28 19:09:09

模式原型Java

2021-10-26 00:21:19

设计模式建造者

2012-01-13 15:59:07

点赞
收藏

51CTO技术栈公众号