【狂神说Java】单例模式-23种设计模式系列_哔哩哔哩_bilibili
推荐狂神的视频,已经被秀了一脸,不知道该怎么做笔记了
饿汉式单例
//饿汉式单例
//单例模式最重要的思想是构造器私有
//内存中只有一个对象
//饿汉式一上来就把对象new出来了
//缺点是有可能浪费内存
public class Hungry {
private Hungry(){
}
private final static Hungry HUNGRY = new Hungry();
public static Hungry getInstance(){
return HUNGRY;
}
}
懒汉式
//懒汉式单例
public class LazyMan {
private LazyMan(){
}
//双重检测锁模式的 懒汉式单例 DCL懒汉式
//volatile 一定要加上这个 放置指令重排序导致的错误
private volatile static LazyMan lazyMan;
public static LazyMan getInstance(){
if (lazyMan == null){
synchronized (LazyMan.class){
if (lazyMan == null){
lazyMan = new LazyMan();//不是一个原子性操作
}
}
}
return lazyMan;
}
}