应用
- 各种Manager
- 各种Factory
单例模式
饿汉
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {
}
private static Singleton getInstance() {
return INSTANCE;
}
}
懒汉
public class Singleton {
private static Singleton INSTANCE;
private Singleton() {
}
private static synchronized Singleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
return INSTANCE;
}
}
懒汉(双重检锁)
public class Singleton {
private static volatile Singleton INSTANCE;
private Singleton() {
}
private static Singleton getInstance() {
if (INSTANCE == null) {
synchronized (Singleton.class) {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
}
}
return INSTANCE;
}
}
静态内部类
public class Singleton {
private static class Holder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton() {
}
private static Singleton getInstance() {
return Holder.INSTANCE;
}
}
枚举
public enum Singleton {
INSTANCE;
private static Singleton getInstance() {
return INSTANCE;
}
}
保护单例
防止序列化
private Object readResolve() {
return getInstance();
}
防止反射
构造器中加入反射拦截代码