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

对单例模式理解上的问题..............
Java code

 public class SingLeton{ 
      private static SingLeton instance = new SingLeton(); 
      public static SingLeton getInstance(){ 
        return instance; 
      } 
    } 




为什么要把instance属性定义成 private 呢,而不是public 
       public static SingLeton instance = new SingLeton();     

定义成private 有什么好处, 其它包的类怎么调用这个(instance )属性啊

------解决方案--------------------
你这个单例有问题,可以说不叫单例,为什么呢?为你没有写他的构造方法,构造方法要写成 private SingLeton (){}

否则,在外面,别人仍然可以使用SingLeton instance = new SingLeton(); 来构造对象。呵呵。
------解决方案--------------------
Java code

public class Singleton {
  private static Singleton instace = null; // private 修饰,避免外部更改
  private Singleton(){}  // 隐藏构造函数
  public static synchronized Singleton getInstance() {  // 同步,避免同时创建多个实例
    if (instance == null) {
      instance = new ...
    }
    return instance;
  }
}

------解决方案--------------------
探讨
Java code
public class Singleton {
private static Singleton instace = null; // private 修饰,避免外部更改
private Singleton(){} // 隐藏构造函数
public static synchronized Singleton getInstance() { // 同步,避免同时创建多个实例
if (instance == null) {
instance = new ...
}
return instance;
}
}

------解决方案--------------------
Java code
public class Singleton{
    private static Singleton instance = new Singleton();

    private SingLeton(){
    }
    public static Singleton getInstance(){
        return instance;
    }
}