在构造函数中,只允许初始化一次即可解决。
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; } }