一、懒汉式
1.懒汉式-非线程安全版
public class LazySingletonClass {
private static LazySingletonClass instance = null;
private LazySingletonClass(){
}
public static LazySingletonClass getInstance(){
if (instance == null){
instance = new LazySingletonClass();
}
return instance;
}
}
2.懒汉式-线程安全
public class LazySingletonClass {
private static LazySingletonClass instance = null;
private LazySingletonClass(){
}
public static synchronized LazySingletonClass getInstance(){
if (instance == null){
instance = new LazySingletonClass();
}
return instance;
}
}
二、饿汉式
public class HungerSingletonClass {
private static HungerSingletonClass instance = new HungerSingletonClass();
private HungerSingletonClass(){
}
public static HungerSingletonClass getInstance(){
return instance;
}
}
三、双检锁/双重校验锁(DCL,即 double-checked locking)
public class DoubleLockSingletonClass {
private static DoubleLockSingletonClass instance;
private DoubleLockSingletonClass() {
}
public static DoubleLockSingletonClass getInstance() {
if (instance == null) {
synchronized (DoubleLockSingletonClass.class) {
if (instance == null) {
instance = new DoubleLockSingletonClass();
}
}
}
return instance;
}
}
四、登记式/静态内部类
public class HolderSingletonClass {
private static class SingletonHolder {
private static HolderSingletonClass INSTANCE = new HolderSingletonClass();
}
private HolderSingletonClass() {
}
public static HolderSingletonClass getInstance() {
return SingletonHolder.INSTANCE;
}
}