
我发现网上单例模式中 getInstance 方法基本上都是这么写的,我觉得这种写法虽然正确但是一点都不易读。 请教各位,像我下面这样写正确吗?
public static synchronized Singleton getInstance(){
if(mInstance == null){
mInstance = new Singleton();
}
return mInstance;
}
1 rails3 Dec 10, 2015 最好的静态内部类 |
2 bqbkbz Dec 10, 2015 经典案例啊,你这个性能要差很多 |
3 zts1993 Dec 10, 2015 第一种 如果不为空 不用加锁,,你这个,自己没看出问题么。。。。 |
4 xufang Dec 10, 2015 |
5 neo2015 Dec 10, 2015 public synchronized static Singleton getInstance(){ if(mInstance == null){ mInstance = new Singleton(); } return mInstance; } private static class SingletonInstance{ } |
6 sun2920989 Dec 10, 2015 你的写法理论上说没问题 但是并发访问的时候不如第一种效率高 单例的东西 永远是需要生成的时候少 已经存在的时候多 |
7 neo2015 Dec 10, 2015 public synchronized static Singleton getInstance(){ if(mInstance == null){ mInstance = SingletonInstanc.mInstance } return mInstance; } private static class SingletonInstance{ private static Signleton mInstance = new Singleton() } |
8 SparkMan Dec 10, 2015 现在更流行用 enum 类型,比 double check 还牛逼 |
9 pixstone Dec 10, 2015 public static synchronized Singleton getInstance(){ 取方法的时候上锁。。。。这效率要多低啊。。。合理的上锁模式是 实例化的时候上锁 防止重复实例。 |
10 baozijun Dec 10, 2015 你这个每次获取对象时都是加锁的,效率非常低.上面的那个有对象直接返回,没有才加锁,然后判断 此时对象的状态 是否为空,空的话创建 |
11 zouxcs Dec 10, 2015 静态内部类整一个 |
12 Totato5749 OP 谢谢诸君,学到了很多。 |
13 ganxiyun Dec 10, 2015 我觉得楼主贴的 DCL 好像 java 不适用吧,难道现在可以这么用了? |
14 ganxiyun Dec 10, 2015 DCL 不是用 // Works with acquire/release semantics for volatile // Broken under Java 1.4 and earlier semantics for volatile class Foo { private volatile Helper helper; public Helper getHelper() { Helper result = helper; if (result == null) { synchronized(this) { result = helper; if (result == null) { helper = result = new Helper(); } } } return result; } // other functions and members... } |
15 unique Dec 10, 2015 |