单例模式(Singleton Pattern) 是Java比较常见的一个设计模式。定义为:保证一个类只有一个实例,并提供全局访问点。
但其实,单例模式并非是绝对安全的。虽然说单例模式对外隐藏了构造方法,保证使用者无法主动去创建对象,但其实我们还是有办法去破坏的。
方法就是使用反射(reflection)
先来实现一个简单的单例模式代码
public class Singleton implements Serializable {
private volatile static Singleton singleton;
private Singleton() {
}
public static Singleton getSingleton(){
if(singleton == null){
synchronized (Singleton.class){
if(singleton == null){
singleton = new Singleton();
}
}
}
return singleton;
}
}
这个Singleton就是单例的,不能通过new对象的形式来获取实例
现在我们通过反射的形式来获取
public class SingletonTest {
public static void main(String[] args) {
Singleton singleton = Singleton.getSingleton();
try {
Class<Singleton> singleClass =(Class<Singleton>) Class.forName("com.dev.test.Singleton");
Constructor<Singleton> constructor = singleClass.getDeclaredConstructor(null);
constructor.setAccessible(true);
Singleton singletonByReflect = constructor.newInstance();
System.out.println("singleton: "+singleton);
System.out.println("singletonByReflect: "+singletonByReflect);
}catch (Exception e){
e.printStackTrace();
}
}
}
运行结果:
如上所示,我们可以通过反射的方式来获取新的单例对象,从而破坏单例
那么,能不能避免单例模式被反射破坏呢?其实是可以的,以上面的单例模式为例,只要在构造函数中加入判断,抛出异常
public class Singleton implements Serializable {
private volatile static Singleton singleton;
private Singleton() {
if (singleton != null) {
throw new RuntimeException("Singleton constructor is private ");
}
}
public static Singleton getSingleton(){
if(singleton == null){
synchronized (Singleton.class){
if(singleton == null){
singleton = new Singleton();
}
}
}
return singleton;
}
}
然后现在再运行我们的反射代码
只要该单例对象已经被使用 Singleton singleton = Singleton.getSingleton(); 再通过反射获取时就会抛出异常,阻止其获取新的实例对象
除了反射,还有其他方法也能破坏单例,比如序列化(序列化+反序列化的方式),这里不详细描述。