首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

对单例模式理解上的有关问题.

2012-02-01 
对单例模式理解上的问题..............Java code public class SingLeton{       private static SingLeto

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

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;    }} 

热点排行