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
}
}