014——static应用知识:单例设计模式

static应用知识:单例设计模式

设计模式

  • 开发中经常遇到一些问题,一个问题通常有n种解法的,但其中肯定有一种解法是最优的,这个最优的解法被人总结出来了,称之为设计模式。

  • 设计模式有20多种,对应20多种软件开发中会遇到的问题。

学设计模式主要是学2点:

  1. 这种模式用来解决什么问题。

  2. 遇到这种问题了,该模式是怎么写的,他是如何解决这个问题的。

单例模式

img

单例的实现方式很多

img

饿汉单例设计模式

  • 在用类获取对象的时候,对象已经提前为你创建好了。

设计步骤

  • 定义一个类,把构造器私有。
  • 定义一个静态变量存储一个对象。

img

案例


package com.north.d4_static_singleinstance;

/**
 * @author North
 * @date 10/6/2022 3:04 PM
 *
 *  使用饿汉单例实现单例类
 */
public class SingleInstance {

    /**
     *  1. 必须把构造器私有化
     */
    private SingleInstance() {

    }

    /**
     *  饿汉单例是在获取对象前 , 对象已经提前准备好了一个
     *  这个对象只能是一个 , 所以定义静态成员变量记住
     */
    public static SingleInstance instance = new SingleInstance();

}



package com.north.d4_static_singleinstance;

/**
 * @author North
 * @date 10/6/2022 3:50 PM
 */
public class Test {
    public static void main(String[] args) {
        SingleInstance singleInstance = SingleInstance.instance;
        SingleInstance singleInstance_1 = SingleInstance.instance;

        // 根据地址来进行判断是否是同一个对象
        System.out.println(singleInstance == singleInstance_1);

    }
}


结果显示


true

懒汉单例模式

懒汉单例设计模式

  • 在真正需要该对象的时候,才去创建一个对象(延迟加载对象)。

设计步骤

img


img

案例演示


package com.north.d4_static_singleinstance;

/**
 * @author North
 * @date 10/6/2022 3:57 PM
 *
 * 懒汉单例
 */
public class SingleInstance02 {

    /**
     *  1. 私有化构造器
     */
    private SingleInstance02() {

    }

    /**
     *  2. 定义一个静态的成员变量负责存储一个对象
     *  只加载一次 , 只有一份
     */
    public static SingleInstance02 instance;

    /**
     *  3. 提供一个编发 ,对外返回单例对象
     */

    public static SingleInstance02 getInstance() {
        // 第一次来拿对象 , 此时需要创建对象
        if (instance == null) {
            instance = new SingleInstance02();
        }
        return instance;
    }
}


测试类


package com.north.d4_static_singleinstance;

/**
 * @author North
 * @date 10/6/2022 3:56 PM
 */
public class Test02 {
    public static void main(String[] args) {
        // 目标 : 掌握懒汉单例的设计 , 理解其思想
        SingleInstance02 singleInstance02 = SingleInstance02.getInstance();
        SingleInstance02 singleInstance02_1 = SingleInstance02.getInstance();

        System.out.println(singleInstance02);
        System.out.println(singleInstance02_1);

        System.out.println(singleInstance02 == singleInstance02_1);
    }
}


返回结果


com.north.d4_static_singleinstance.SingleInstance02@1b6d3586
com.north.d4_static_singleinstance.SingleInstance02@1b6d3586
true


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值