单例模式的实现:
1, 普通模式:
public class SingleDemo {
private static SingleDemo instance;
private SingleDemo() {}
public SingleDemo getInstance() {
if (instance == null) {
instance = new SingleDemo();
}
return instance;
}
}以上模式为懒汉模式
可以改造为饥饿模式,即Class加载即new对象
public class SingleDemo {
private static SingleDemo instance = new SingleDemo();
private SingleDemo() {}
public SingleDemo getInstance() {
return instance;
}
}
上述方法可以可以通过反射,突破单例模式。
可以使用 enum方式实现
public enum SingleDemoEnum {
INSTANCE;
public void method() {
// do work.
}
}
本文介绍了单例模式的两种实现方式——懒汉模式和饥饿模式,并探讨了如何通过反射破坏单例模式,最后介绍了一种更安全的实现方式——枚举单例。
991





