/**
* 懒汉模式
* */
public class Singleton1 {
private volatile static Singleton1 instance = null;
private Singleton1() {}
public static Singleton1 getNewInstance() {
if(null == instance) {
synchronized (Singleton1.class) {
if(null == instance) {
instance = new Singleton1();
}
}
}
return instance;
}
}
/**
* 贪婪模式
* */
public class Singleton2 {
private static Singleton2 instance = new Singleton2();
private Singleton2() {}
public static Singleton2 getInstance() {
return instance;
}
}
/**
* 嵌套类模式
* */
public class Singleton3 {
private Singleton3() {}
public static Singleton3 getInstance() {
return SingletonHelper.instance;
}
// 嵌套类
private static final class SingletonHelper{
private static final Singleton3 instance = new Singleton3();
}
}