日期:2014-05-20  浏览次数:20685 次

java 单例类 总是出问题:可以在 类中访问private
class singleton
{  

  private static singleton instance;
  private singleton() { }
  private singleton getinstance()
  {  
  if (instance==null)
  { 
  instance=new singleton();
  }
  return instance;
  }


}



public class testsingleton
{  
   
   
  public static void main(String[] args)
  {
  singleton s1=singleton.getinstance();
  singleton s2=singleton.getinstance();
  System.out.println(s1==s2);
   
  }
}

------解决方案--------------------
class singleton
{

private static singleton instance;
private singleton() { }
private singleton getinstance()
{
if (instance==null)
{
instance=new singleton();
}
return instance;
}

}



public class testsingleton
{


public static void main(String[] args)
{
singleton s1=singleton.getinstance();
singleton s2=singleton.getinstance();
System.out.println(s1==s2);

}
}


红色应该修改为:

 public static singleton getinstance()
{
if (instance==null)
{
instance=new singleton();
}
return instance;
}

必须定义为静态方法,同时应该为public,否则外部类没办法通过类名.getinstance()获得单例类的示例