首页 > 代码库 > 单例模式防止反射和反序列化

单例模式防止反射和反序列化

public class SingletonDemo5 implements Serializable{
private static SingletonDemo5 instance;
//防止单例被反射
private SingletonDemo5(){
if(null!=instance){
throw new RuntimeException("不能被反射");
}
}
/* public static synchronized SingletonDemo2 getInstance(){

if(null==instance){
return instance=new SingletonDemo2();
}

return instance;
}*/
//资源不够优化,可以进行双重检查,注释部分
public static SingletonDemo5 getInstance(){
//双重检查,提高效率
if(null==instance){
synchronized (SingletonDemo5.class) {
if(null==instance){
instance=new SingletonDemo5();
}

}

}

return instance;
}
//当反序列化的时候,直接调用当前的对象
private Object readResolve(){
return instance;
}
}

 

public class Test2 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
SingletonDemo5 s1=SingletonDemo5.getInstance();
SingletonDemo5 s2=SingletonDemo5.getInstance();
System.out.println(s1);
System.out.println(s2);

//注释  readResolve()方法的时候
//s1 com.my.design.single.SingletonDemo5@15db9742
//s2 com.my.design.single.SingletonDemo5@15db9742
//s3 com.my.design.single.SingletonDemo5@e9e54c2
File file=new File("d:/a.txt");
FileOutputStream fos=new FileOutputStream(file);
ObjectOutputStream os=new ObjectOutputStream(fos);
os.writeObject(s1);
ObjectInputStream is=new ObjectInputStream(new FileInputStream(file));
SingletonDemo5 s3=(SingletonDemo5) is.readObject();
System.out.println(s3);
}
}

//没注释 readResolve()方法的时候

//s1 com.my.design.single.SingletonDemo5@15db9742

//s2 com.my.design.single.SingletonDemo5@15db9742

//s3 com.my.design.single.SingletonDemo5@15db9742

前面是防止反序列化,如果要防止反射的话可以在构造器中抛出异常

单例模式防止反射和反序列化