美文网首页
android 官方实现的单例工具类

android 官方实现的单例工具类

作者: 國軍哥哥 | 来源:发表于2018-05-08 15:48 被阅读0次

简述

今天在看Activity启动过程的时候,看到一个超级棒的单例实现方式,在这做下记录,

工具类

/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
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;
        }
    }
}

具体使用,参见Android源码ActivityManagerNative

    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;
        }
    };
    
    
    /**
     * Retrieve the system's default/global activity manager.
     */
    static public IActivityManager getDefault() {
        return gDefault.get();
    }
    

相关文章

  • android 官方实现的单例工具类

    简述 今天在看Activity启动过程的时候,看到一个超级棒的单例实现方式,在这做下记录, 工具类 具体使用,参见...

  • Android笔记-3:重读单例模式有感(续)

    Android笔记-2:重读单例模式有感这篇中最后写道还要重写工具类改为单例模式。 有读者其实应该发现上篇文章中用...

  • 单例模式

    什么是单例模式? 一个类只允许创建一个实例,那个类就是单例类。这个模式就是单例模式。单例模式实现方式:饿汉式:实现...

  • 单例模式

    1.利用装饰器实现单例模式 2.修改new方法实现单例模式 3.利用元类实现单例模式 总结: 用装饰器和元类实现的...

  • Kotlin中的单例实现原理

    1.使用Object关键字进行单例类声明 2.单例类的使用 3. 单例类的实现原理

  • Java学习笔记2

    Singleton / 不可变类 / 缓存不可变类 的实现 Singleton(单例类) 单例类用的地方很多,如果...

  • python面试题-2018.1.30

    问题:如何实现单例模式? 通过new方法来实现单例模式。 变体: 通过装饰器来实现单例模式 通过元类来创建单例模式...

  • kotlin-5、类与对象

    创建空类 构造函数 调用构造函数 继承 接口 实现接口 data类 最简单的单例 自己实现单例

  • Python实现单例模式

    1.使用__new__实现 2.使用装饰器实现单例 3.类装饰器实现单例 4.元类实现

  • Python两种方式实现单例模式

    装饰器模式实现单例 通过拦截类创建的是模式实现单例 测试结果

网友评论

      本文标题:android 官方实现的单例工具类

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