单例模式— DCL double check lock
public class SingletonDemo {
public static volatile SingletonDemo instance = null;
public SingletonDemo() {
}
public static SingletonDemo getInstance() {
if (instance == null) {
synchronized (SingletonDemo.class) {
if (instance == null) {
instance = new SingletonDemo();
}
}
}
return instance;
}
}
单例模式 饿汉模式 静态常量
简单粗暴
public class SingletonTest {
private final static SingletonTest INSTANCE = new SingletonTest();
private SingletonTest() {
}
public static SingletonTest getInstance() {
return INSTANCE;
}
}
静态代码块
public class Singleton {
private static Singleton instance;
static {
instance = new Singleton();
}
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
静态内部类
public class SingletonDemo {
private SingletonDemo() {
}
private static class SingletonInstance {
private static final SingletonDemo INSTANCE = new SingletonDemo();
}
public static SingletonDemo getInstance() {
return SingletonInstance.INSTANCE;
}
}