首页 > 系统 > Android > 正文

Android 单例模式最好的写法

2019-11-09 15:12:18
字体:
来源:转载
供稿:网友

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

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,都行。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表