public class Interview2 {
/* 一共三种方法,如下:*/
// 方法1
/*private static final Interview2 singleton = new Interview2();
private Interview2(){}
public static Interview2 getInstance(){return singleton;}*/
//方法2
/*private static Interview2 singleton = null;
public static synchronized Interview2 getInstance(){
if(singleton==null){
singleton=new Interview2();
}
return singleton;
}
private Interview2(){}*/
//方法3 双重锁
private static volatile Interview2 singleton = null;
public static Interview2 getInstance(){
if(singleton==null){
synchronized (Interview2.class) {
if(singleton==null){
singleton=new Interview2();
}
}
}
return singleton;
}
private Interview2(){}
}
<剑指offer 面试题2> 单例模式 (Java实现)
最新推荐文章于 2020-09-04 00:27:23 发布