首页 > 技术文章 > 设计模式之单例模式(懒汉式)

bigswallow 2017-10-18 22:01 原文

**
* @author niit
*"懒汉单例式" 定义类的时候不会直接实例化创建出来,而是在第一次调用
*getIntance方法的时候才创建唯一的出来
*
*也要static的修饰那个实例
*构造方法也是要private的
*/
public class Student1 {
//1,先把要实例化的对象定义出来
private static Student1 Instance;
// 2,构造函数私有,保证不能在外部实例化
private Student1(){}

// 3,提供一个公开静态的方法去访问,此时要new出来实例化对象
public static Student1 getInstance(){
if (!(Instance==null)) {
Instance=new Student1();
}
return Instance;

}
}

 测试类


public class Test {
public static void main(String[] args) {
// 因为Student类中的方法是静态的,所以类名.方法名可以直接访问
Student s1=Student.getInstance();
s1.i=666;

Student s2=Student.getInstance();
System.out.println(s2.i);
System.out.println(s1==s2);



}
}

推荐阅读