懒汉式
public class Singleton{
private static Singleton singleton;
private Singleton() {}
public static Singleton getInstance() {
if(null == singleton) {
singleton = new Singleton();
}
return singleton;
}
}
饿汉式
public class Singleton{
private static Singleton singleton = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return singleton;
}
}
双检锁
public class Singleton{
private static volatile Singleton singleton;
private Singleton() {}
public static Singleton getInstance() {
if (null == singleton){
synchronized (Singleton.class){
if (null == singleton){
singleton = new Singleton();
}
}
}
return singleton;
}
}
枚举
public enum Singleton{
INSTANCE(new Test());
private Test test;
Singleton(Test test) {
this.test = test;
}
public Test getTest() {
return test;
}
}