我正在设计下面的单例类,我知道我的单例可能会被破坏
public class SingletonObject {
private static SingletonObject ref;
private SingletonObject () //private constructor
{ }
public static synchronized SingletonObject getSingletonObject()
{
if (ref == null)
ref = new SingletonObject();
return ref;
}
public Object clone() throws CloneNotSupportedException
{throw new CloneNotSupportedException ();
}
}
下面的 url 已经建议了可以用其他方式破解单例的地方,但我的疑问是,正如这个 url 中所建议的那样,单例可以被类加载器破坏,同样的类也可以由两个不同的类加载器加载,因此,你可以只需在由两个不同类加载器加载的类中调用其 getInstance() 方法,即可创建单例类的两个实例。这种方法可以在不必诉诸于违反私有构造函数的情况下起作用。
ClassLoader cl1 = new URLClassLoader(new URL[]{"singleton.jar"}, null);
ClassLoader cl2 = new URLClassLoader(new URL[]{"singleton.jar"}, null);
Class<?> singClass1 = cl1.loadClass("hacking.Singleton");
Class<?> singClass2 = cl2.loadClass("hacking.Singleton");
//...
Method getInstance1 = singClass1.getDeclaredMethod("getInstance", ...);
Method getInstance2 = singClass2.getDeclaredMethod("getInstance", ...);
//...
Object singleton1 = getInstance1.invoke(null);
Object singleton2 = getInstance2.invoke(null);
请告知应采取什么措施来避免这种情况。