程序员地瓜哥的小屋

Java中的单例模式

2021-12-27  本文已影响0人  CodingDGSun

单例模式简介

饿汉模式

//饿汉模式
public class Hungry {
    private static Hungry hungry = new Hungry();

    private Hungry() {

    }

    public static Hungry getInstance() {
        return hungry;
    }
}

懒汉模式(单线程)

public class LazyMan01 {
    private static LazyMan01 lazyMan;

    private LazyMan01() {
    }

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

懒汉模式(多线程)

public class LazyMan02 {
    private volatile static LazyMan02 lazyMan;

    private LazyMan02() {
    }

    //双重检测锁 懒汉单例模式 DCL懒汉模式
    public static LazyMan02 getInstance() {
        if (lazyMan == null) {
            synchronized (LazyMan02.class) {
                if (lazyMan == null) {
                    lazyMan = new LazyMan02();
                }
            }
        }
        return lazyMan;
    }
}
上一篇下一篇

猜你喜欢

热点阅读