栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

static应用——两种单例模式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/697420.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号