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

java 单列问题
public class Test {

private static Test unique=new Test();//为什么要静态化
private Test(){//为什么要定义构造方法 为什么要把构造方法写成私有的  

}
public static Test getInstance(){
if(unique==null){
unique=new Test();
}
return unique;
}

}

------解决方案--------------------
这个单例写错了吧。。。应该是:

public class Test {
private static Test unique=new Test(); // 静态化才能让静态方法可以直接访问,也就是getInstance()

private Test(){// 为了避免外部类误写 new Test(),从而破坏了“单例”模式,所以让其“不可见”
}

public static Test getInstance(){
return unique; // 定义时就已经初始化好了,这里直接返回即可
}
}