您的位置:首页 > 其它

单例模式实现方式

2016-10-09 10:51 169 查看
public class Singleton {

private Singleton() {}

// Lazy initialization holder class idiom for static fields
private static class InstanceHolder {
private static final Singleton instance = new Singleton();
}

public static Singleton getSingleton() {
return InstanceHolder.instance;
}
}


public class LazySingleton {
private int someField;

private static LazySingleton instance;

private LazySingleton() {
this.someField = new Random().nextInt(200)+1;         // (1)
}

public static LazySingleton getInstance() {
if (instance == null) {                               // (2)
synchronized(LazySingleton.class) {               // (3)
if (instance == null) {                       // (4)
instance = new LazySingleton();           // (5)
}
}
}
return instance;                                      // (6)
}

public int getSomeField() {
return this.someField;                                // (7)
}
}


上面这种方式完美,下面这种方式极小可能会出现happen—before问题,导致调用getSomeField()方法返回0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: