懒汉单例模式:再用类获取对象的时候,对象已经提前创建好了
在拿对象的时候比较方便更快。
package com.itheima.demo1;
//目标:使用饿汉单例方式定义单例类
public class SingLeInstance1 {
/**
* 2.定义一个公开的静态的成员变量储存一个类的对象,
* 饿汉:在这里加载静态变量的时候就会创建对象了
*/
public static SingLeInstance1 instance = new SingLeInstance1();
/**
* 1.把构造器私有起来
*/
private SingLeInstance1(){
}
}
下面做了一个测试类
package com.itheima.demo1;
public class Test1 {
public static void main(String[] args) {
SingLeInstance1 S1 = SingLeInstance1.instance;
SingLeInstance1 S2 = SingLeInstance1.instance;
SingLeInstance1 S3 = SingLeInstance1.instance;
System.out.println(S1);
System.out.println(S2);
System.out.println(S3);
System.out.println(S1 == S3);
}
}
懒汉单例模式:在真正需要该对象的时候,才去创建对象。
节省内存。
package com.itheima.demo1;
//目标:学会懒汉单例模式定义单例类
public class SingLeInstance2 {
//2.创建一个静态成员变量储存一个类的对象,注意:此次对线不能初始化
//public static SingLeInstance2 instance;
private static SingLeInstance2 instance;
/**
* 1.把构造器先私有
*/
private SingLeInstance2(){
}
/**
* 3.定义一个方法,让其他方法来调用获取一个对象
*/
public static SingLeInstance2 instance2(){
if(instance == null){
//第一次来获取对象
instance = new SingLeInstance2();
}
return instance;
}
}
下面是测试类
package com.itheima.demo1;
public class Test2 {
public static void main(String[] args) {
SingLeInstance2 s1 = SingLeInstance2.instance2();
SingLeInstance2 s2 = SingLeInstance2.instance2();
SingLeInstance2 s3 = SingLeInstance2.instance2();
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s1 == s3);
}
}
其实这两个没有太大的差别,用哪个还是需要看项目的需要。但是这两个面试可能会遇见,可能会让你手写一个单例模式的算法,建议代码可以记记。 这上面标的1.2.3.就是步骤,我就不再重复写一遍了。
注意:在懒汉单例模式中,第二步,一般高手会把这个成员对象私有化,这样在测试类的时候就不会显示这个对象(为了以防公开会被别人误会),只会显示下面的方法了。