美文网首页
Android源码泛型实现单例基类

Android源码泛型实现单例基类

作者: Frankeen | 来源:发表于2018-12-06 17:44 被阅读13次
    基类
    package android.util;
    
    /**
     * Singleton helper class for lazily initialization.
     *
     * Modeled after frameworks/base/include/utils/Singleton.h
     *
     * @hide
     */
    public abstract class Singleton<T> {
        private T mInstance;
    
        protected abstract T create();
    
        public final T get() {
            synchronized (this) {
                if (mInstance == null) {
                    mInstance = create();
                }
                return mInstance;
            }
        }
    
    使用
    private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() {
            protected IActivityManager create() {
                IBinder b = ServiceManager.getService("activity");
                if (false) {
                    Log.v("ActivityManager", "default service binder = " + b);
                }
                IActivityManager am = asInterface(b);
                if (false) {
                    Log.v("ActivityManager", "default service = " + am);
                }
                return am;
            }
        };
    

    相关文章

      网友评论

          本文标题:Android源码泛型实现单例基类

          本文链接:https://www.haomeiwen.com/subject/mqkocqtx.html