1.什么是单例模式
单例模式必须满足以下两点要求
- 私有化构造函数
- 全局唯一的共有访问点
2.懒汉式单例
public class Lazy {
private static Lazy instance;
private Lazy(){}
public static Lazy getInstance(){
if (instance == null){
synchronized (Lazy.class){
if (instance == null) {
instance = new Lazy();
}
}
}
return instance;
}
}
3.饿汉式单例
public class Hungry {
private static final Hungry instance = new Hungry();
private Hungry() {
}
public static Hungry getInstance() {
return instance;
}
}
4.利用反射破坏单例
public class SingletonDestroyer {
public static void main(String[] args) throws Exception {
Lazy lazyInstance = Lazy.getInstance();
Constructor constructor = Lazy.class.getDeclaredConstructor();
constructor.setAccessible(true);
Lazy lazyInstanceReflect = (Lazy) constructor.newInstance();
System.out.println(lazyInstance == lazyInstanceReflect); // false
}
}