package test;
class 单例设计模式测试 {
//构造方法私有化
private 单例设计模式测试() {}
//属性私有化
private String usname;
private String pwd;
//本类实例化私有化
private static 单例设计模式测试 单例=new 单例设计模式测试();
//利用getter方法取得本类实例对象
public static 单例设计模式测试 getInstance() {
return 单例;
}
//本类方法
public void print() {
System.out.println("6666");
}
}
public class 单例设计模式{
public static void main(String[] args) {
单例设计模式测试 test=单例设计模式测试.getInstance();
test.print();//666
}
}
但是我们发现
public static 单例设计模式测试 getInstance() {
return 单例;
}
这个方法里面仍然有漏洞,因为存在
public static 单例设计模式测试 getInstance() {
instance =new 单例设计模式();
return 单例;
}
所以在设计时加上final,使其变成一个常量
final private static 单例设计模式测试 单例=new 单例设计模式测试();