餓漢式
public class Singleton{
private static volatile Singleton instance = new Singleton();
private Singleton(){}
public static Singleton getInstance() {
return instance;
}
}
懶漢式
public class Singleton{
private static Singleton instance示损;
private Singleton(){}
public static Singleton getInstance() {
if(instance == null){
intance = new Singleton():
}
return instance;
}
}
雙重檢測
public class Singleton {
private static volatile Singleton instance = null;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
靜態(tài)內(nèi)部類
class Singleton{
private static class SingletonDemo{
private final static Singleton INSTANCE = new Singleton();
}
private Singleton(){}
private static final Singleton getInstance() {
return SingletonDemo.INSTANCE;
}
}
枚舉類
public enum Singleton{
INSTANCE;
public void instance(){}
}