单例模式

package com.dimpt.panorama.rest;

public class Single {

}

//饿汉式单例 class Hungry{

//可能会浪费空间
private byte[] data1 = new byte[1024];
private byte[] data2 = new byte[1024];
private byte[] data3 = new byte[1024];
private byte[] data4 = new byte[1024];

private Hungry(){};

private final static Hungry HUNGRY = new Hungry();

public static Hungry getInstance(){
    return HUNGRY;
}

}

//懒汉式单例 class LazyMan{

private LazyMan(){};

private static LazyMan lazyMan ;

public static LazyMan getInstance() {
    if (lazyMan == null) {
        lazyMan = new LazyMan();
    }
    return lazyMan;
}

}

//懒汉式在多线程并发下会出现问题 //DCL双重检测锁 class DCLLazy{

private DCLLazy(){};

private volatile static DCLLazy DCL_LAZY;

public static  DCLLazy getInstance(){
    if(DCL_LAZY == null) {
        synchronized (DCLLazy.class){
            if (DCL_LAZY==null) {
                DCL_LAZY = new DCLLazy();//不是一个原子性操作
                /**
                 * 1.分配内存空间
                 * 2.执行构造方法,初始化对象
                 * 3.把这个对象指向这个空间
                 *
                 * 正常new对象的执行顺序是123,但是多线程下可能会执行132,返回了一个没有执行构造方法的对象,所以此处我们要加上volatile关键字,避免指令重排
                 */

            }
        }
    }
    return DCL_LAZY;

}

}

//枚举实现单例模式 enum EnumSingle {

INSTANCE;

public EnumSingle getInstance() {
    return INSTANCE;
}

}


本文章使用limfx的vscode插件快速发布