Android和设计模式:享元模式

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

    享元模式是一种针对大量细粒度对象有效使用的一种模式。Android中的Message、Parcel和TypedArray都利用了享元模式。以Message为例,类图如下:
clip_image002
    其中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;
    }
}

你可能感兴趣的:(android,message,parcel,享元模式,TypedArray)