static应用——两种单例模式

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

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

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值