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

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);spa

//註釋  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@15db9742get

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

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

前面是防止反序列化,若是要防止反射的話能夠在構造器中拋出異常class

相關文章
相關標籤/搜索