登录
  • 欢迎访问 Sharezer Blog

Android 单例模式最好的写法

Android sharezer 来源:赵勇Yaphet 2141次浏览 已收录 0个评论

一般来说,通常写法是这样的:

public class Singleton {
    private static Singleton instance;
    private Singleton (){}

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

这种写法线程不安全,所以有的是加线程锁,加了之后是这样的:

public class Singleton {
    private static Singleton instance;
    private Singleton (){}
    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

这样写挺好的,就是效率低,增加效率的写法:

public class Singleton {
    private volatile static Singleton singleton;
    private Singleton (){}
    public static Singleton getSingleton() {
        if (singleton == null) {
            synchronized (Singleton.class) {
                if (singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }
}

上面用的是最多的,也比较推荐,挺好的。
还有一种静态内部类写法是这样的:

publlic class Singleton {
    private Singleton() {}
    private static class SingletonLoader {
        private static final Singleton INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
        return SingletonLoader.INSTANCE;
    }
}

推荐使用静态内部类写法,或者volatile+synchronized,都行。


Sharezer , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明Android 单例模式最好的写法
喜欢 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址