设计模式-单例模式

1、饿汉模式

/**
 * @author joy
 * @Package gof23
 * @Description: 单例模式之饿汉式单例模式
 * @date 2022/3/11 10:23
 */
public class Hungry {
    private static Hungry hungry = new Hungry();
    //私有化构造器:单例模式的核心思想
    private Hungry() {
    }
    public static Hungry getInstance() {
        return hungry;
    }
}

2、懒汉模式

/**
 * @author joy
 * @Package gof23
 * @Description: 单例模式之懒汉式,线程不安全,可以改为双重检验锁模式
 * @date 2022/3/11 10:29
 */
public class LazyMan {
    private static LazyMan lazyMan;

    private LazyMan() {
    }

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

3、双重检验锁模式

/**
 * @author joy
 * @Package gof23
 * @Description: 单例模式懒汉式的双重检验锁模式,线程安全
 * @date 2022/3/11 10:37
 */
public class LazyManSyn {
    private static volatile LazyManSyn lazyManSyn;//使用此关键字是为了防止指令重排
    private LazyManSyn(){

    }
    public static LazyManSyn getInstance(){
        if(lazyManSyn == null){
            synchronized(LazyManSyn.class){//synchronized代码块是悲观锁
                if(lazyManSyn == null){
                    lazyManSyn = new LazyManSyn();
                }
            }
        }
        return lazyManSyn;
    }
}
posted @ 2022-03-14 15:59  刘小呆  阅读(14)  评论(0编辑  收藏  举报