static应用——两种单例模式

static应用——两种单例模式,第1张

static应用——两种单例模式

懒汉单例模式:再用类获取对象的时候,对象已经提前创建好了

在拿对象的时候比较方便更快。

package com.itheima.demo1;

//目标:使用饿汉单例方式定义单例类
public class SingLeInstance1 {
    
    public static SingLeInstance1 instance = new SingLeInstance1();


    
    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;


    
  private  SingLeInstance2(){

  }


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.就是步骤,我就不再重复写一遍了。

注意:在懒汉单例模式中,第二步,一般高手会把这个成员对象私有化,这样在测试类的时候就不会显示这个对象(为了以防公开会被别人误会),只会显示下面的方法了。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5697552.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存