Android和设计模式:享元模式

 
    最近在继续iPhone 业务的同时还须要从新拾起Android 。在有些生疏的状况下,决定从Android 源码中感悟一些Android 的风格和方式。在学习源码的过程当中也发现了一些通用的模式,但愿经过一个系列的文章总结和分享下。

    享元模式是一种针对大量细粒度对象有效使用的一种模式。Android中的Message、Parcel和TypedArray都利用了享元模式。以Message为例,类图以下:
clip_p_w_picpath002
    其中Message经过next成员变量保有对下一个Message的引用,从而构成了一个Message链表。Message Pool就经过该链表的表头管理着全部闲置的Message,一个Message在使用完后能够经过recycle()方法进入Message Pool,并在须要时经过obtain静态方法从Message Pool获取。实现代码以下:
public final class Message implements Parcelable {
    ......
    // sometimes we store linked lists of these things
    /*package*/ Message next;
    private static final Object sPoolSync = new Object();
    private static Message sPool;
    private static int sPoolSize = 0;
    private static final int MAX_POOL_SIZE = 10;     /**      * Return a new Message instance from the global pool. Allows us to      * avoid allocating new objects in many cases.      */     public static Message obtain() {         synchronized (sPoolSync) {             if (sPool != null) {                 Message m = sPool;                 sPool = m.next;                 m.next = null;                 sPoolSize--;                 return m;             }         }         return new Message();     }     ......     public void recycle() {         synchronized (sPoolSync) {             if (sPoolSize < MAX_POOL_SIZE) {                 clearForRecycle();                 next = sPool;                 sPool = this;                 sPoolSize++;             }         }     }     ......     /*package*/ void clearForRecycle() {         what = 0;         arg1 = 0;         arg2 = 0;         obj = null;         replyTo = null;         when = 0;         target = null;         callback = null;         data = null;     } }
相关文章
相关标签/搜索