设计模式之单例模式(创建型)

本文详细介绍了Java中实现单例模式的三种常见方法:饿汉式、懒汉式以及在多线程环境下确保线程安全的双重检查写法。通过代码示例展示了每种方式的实现细节,帮助理解单例模式的设计原则和在实际应用中的考虑因素。
摘要由CSDN通过智能技术生成

单例模式定义:保证一个类只有一个实例,并提供一个访问它的全局访问点。

创建单例模式的几种方法:

1、饿汉式

顾名思义就是“很懒”,我不管你用不用,一上来就创建对象。

代码如下:

/**
 * “饿汉式”:是在不管你用的用不上,一开始就建立这个单例对象
 */
public class SingletonManagerHungry {

    //产生唯一静态私有的实例化对象
    private static SingletonManagerHungry instance = new SingletonManagerHungry();

    //私有化构造函数
    private SingletonManagerHungry() {

    }

    //提供对外的静态方法获取唯一的实例
    public static SingletonManagerHungry getInstance() {
        return instance;
    }

}

2、懒汉式

顾名思义,我“很懒”,用的时候我才创建。

代码如下:

public class SingletonManagerLazy {

    private static SingletonManagerLazy singletonManagerLazy = null;

    //私有化构造函数
    private SingletonManagerLazy() {

    }

    public static SingletonManagerLazy getInstance() {
        if(singletonManagerLazy == null) { 
            singletonManagerLazy = new SingletonManagerLazy();
        }
        return singletonManagerLazy;
    }

}

3、单例模式的多线程安全双重检查写法

如果在多线程情况下,同时创建对象,如何保证只创建一个对象?

代码如下:

public class SingletonManagerLazy {

    private static SingletonManagerLazy singletonManagerLazy = null;

    //私有化构造函数
    private SingletonManagerLazy() {

    }

    public static SingletonManagerLazy getInstance() {
        //先检查实例是否存在,如果不存在才进入下面的同步块
        if(singletonManagerLazy == null) {
            //同步块,线程安全的创建实例
            synchronized (SingletonManagerLazy.class) {
                //再次检查实例是否存在,如果不存在才真的创建实例
                if(singletonManagerLazy == null) {
                    singletonManagerLazy = new SingletonManagerLazy();
                }
            }
        }
        return singletonManagerLazy;
    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值