陆小叁
这是一个充满鲜花的世界

单例模式的定义

个人理解,单例是指单个实例,在整个应用程序当中有且仅有一个实例存在,该实例是通过代码指定好的(自行创建的)。

为什么要使用

  1. 解决在高并发过程中,多个实例出现逻辑错误的情况。
  2. 在特定的业务场景下避免对象重复创建,节约内存。

实现的两种方式

饿汉式

顾名思义,不管有没有使用到该对象,只要程序启动成功,该单实例对象就存在。

代码如下:

/**
 * 饿汉式
 */
public class SingletonHungry {


    private static SingletonHungry instance = new SingletonHungry();

    public static SingletonHungry instance(){
        return instance;
    }

    public static void main(String[] args) {
        SingletonHungry instance1 = SingletonHungry.instance();
        SingletonHungry instance2 = SingletonHungry.instance();
        System.out.println(instance1);
        System.out.println(instance2);
    }
}

上述情况,满足在单线程和多线程中使用。

懒汉式

顾名思义,只有在程序当中使用到该对象的时候,该单实例对象才会被实例化。

代码如下:

/**
 * 懒汉式-单线程
 */
public class SingletonLazy {

    public static SingletonLazy instance = null ;

    public static SingletonLazy instance() {
        if(instance == null) {
            instance = new SingletonLazy() ;
        }

        return instance ;
    }
}

上述编写的代码中,乍一看,没问题,满足了单实例对象。可是细细一琢磨,咋感觉这不对,如果多线程情况下,就很难保证单实例对象了。下面提供一种多线程情况下实现单例的方式:

/**
 * 懒汉式-多线程
 */
public class SingletonLazy {

    public static SingletonLazy instance = null ;

    public static SingletonLazy instance() {

        if(instance == null ) {
            synchronized (SingletonLazy.class) {
                if(instance == null) {
                    instance = new SingletonLazy();
                }
            }
        }
        return instance ;
    }
}

上述的代码中满足了多线程的使用场景,就是使用了上锁+双重检查来进行实现。

欢迎交流!

posted on 2021-08-17 10:27  陆小叁  阅读(804)  评论(0编辑  收藏  举报