在构造函数中,只允许初始化一次即可解决。
public class Singleton {
private static boolean flag=false;
private static Singleton instance=null;
private Singleton(){
if(flag==false){
flag=!flag;
}else {
throw new RuntimeException("单例模式被攻击");
}
}
public static synchronized Singleton getInstance(){
if(instance==null){
instance=new Singleton();
}
return instance;
}
}
本文深入探讨了单例模式的实现方式,并提出了一种防御性编程策略,以防止单例模式遭受多重实例化的攻击。通过在构造函数中设置标志位,确保在整个应用周期内仅创建一次单例对象。
534

被折叠的 条评论
为什么被折叠?



