来源:朱小厮
链接:blog.csdn.net/u013256816/article/details/50525335
单例模式相信大家都知道,用过的人不在少数。之前写过一篇博文《singleton模式四种线程安全的实现》(参见:http://blog.csdn.NET/u013256816/article/details/50427061),讲诉了单例模式的四种写法,并指出占位符模式的写法比较ok,详见如下:
package com.effective.singleton;
public class Elvis
{
private static boolean flag = false;
private Elvis(){
}
private static class SingletonHolder{
private static final Elvis INSTANCE = new Elvis();
}
public static Elvis getInstance()
{
return SingletonHolder.INSTANCE;
}
public void doSomethingElse()
{
}
}
但这都是基于一个条件:确保不会通过反射机制调用私有的构造器。
这里举个例子,通过JAVA的反射机制来“攻击”单例模式:
package com.effective.singleton;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class ElvisReflectAttack
{
public static void main(String[] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException
{
Class<?> classType = Elvis.class;
Constructor<?> c = classType.getDeclaredConstructor(null);
c.setAccessible(true);
Elvis e1 = (Elvis)c.newInstance();
Elvis e2 = Elvis.getInstance();
System.out.println(e1==e2);
}
}
运行结果:false
可以看到,通过反射获取构造函数,然后调用setAccessible(true)就可以调用私有的构造函数,所有e1和e2是两个不同的对象。
如果要抵御这种攻击,可以修改构造器,让它在被要求创建第二个实例的时候抛出异常。
经修改后:
package com.effective.singleton;
public class ElvisModified
{
private static boolean flag = false;
private ElvisModified(){
synchronized(ElvisModified.class)
{
if(flag == false)
{
flag = !flag;
}
else
{
throw new RuntimeException("单例模式被侵犯!");
}
}
}
private static class SingletonHolder{
private static final ElvisModified INSTANCE = new ElvisModified();
}
public static ElvisModified getInstance()
{
return SingletonHolder.INSTANCE;
}
public void doSomethingElse()
{
}
}
测试代码:
package com.effective.singleton;
import java.lang.reflect.Constructor;
public class ElvisModifiedReflectAttack
{
public static void main(String[] args)
{
try
{
Class<ElvisModified> classType = ElvisModified.class;
Constructor<ElvisModified> c = classType.getDeclaredConstructor(null);
c.setAccessible(true);
ElvisModified e1 = (ElvisModified)c.newInstance();
ElvisModified e2 = ElvisModified.getInstance();
System.out.println(e1==e2);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
运行结果:
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.effective.singleton.ElvisModified.getInstance(ElvisModified.java:27)
at com.effective.singleton.ElvisModifiedReflectAttack.main(ElvisModifiedReflectAttack.java:17)
Caused by: java.lang.RuntimeException: 单例模式被侵犯!
at com.effective.singleton.ElvisModified.<init>(ElvisModified.java:16)
at com.effective.singleton.ElvisModified.<init>(ElvisModified.java:7)
at com.effective.singleton.ElvisModified$SingletonHolder.<clinit>(ElvisModified.java:22)
... 2 more
可以看到,成功的阻止了单例模式被破坏。
从JDK1.5开始,实现Singleton还有新的写法,只需编写一个包含单个元素的枚举类型。推荐写法:
package com.effective.singleton;
public enum SingletonClass
{
INSTANCE;
public void test()
{
System.out.println("The Test!");
}
}
测试代码:
package com.effective;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import com.effective.singleton.SingletonClass;
public class TestMain
{
public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
{
Class<SingletonClass> classType = SingletonClass.class;
Constructor<SingletonClass> c = (Constructor<SingletonClass>) classType.getDeclaredConstructor();
c.setAccessible(true);
c.newInstance();
}
}
运行结果:
Exception in thread "main" java.lang.NoSuchMethodException: com.effective.singleton.SingletonClass.<init>()
at java.lang.Class.getConstructor0(Unknown Source)
at java.lang.Class.getDeclaredConstructor(Unknown Source)
at com.effective.TestMain.main(TestMain.java:22)
由此可见这种写法也可以防止单例模式被“攻击”。
而且这种写法也可以防止序列化破坏单例模式,具体不在举例了,有关序列化以及单例模式被序列化破坏可以参考博文《JAVA序列化》(链接:http://blog.csdn.net/u013256816/article/details/50474678)。
单元素的枚举类型已经成为实现Singleton模式的最佳方法。
网友评论