mybloger

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

单例模式五种方式

饿汉式

public class Singleton{
    private static final Singleton instance = new Singleton();
    private Singleton() { // 防止暴力反射
        if (instance != null) {
            throw new RunTimeException("单例对象不能重复被创建");
        }
        System.out.println("new Singleton...");
    };
    public static Singleton getInstance() {
        return instance;
    }
    public Object readResolve() { // 防止反序列化破坏单例
        return instance;
    }
}

饿汉枚举

public Enum Singleton{
    INSTANCE;
}

懒汉式

public class Singleton {
    private static final Singleton instance = null;
    private Singleton(){}
    public static synchronized Singleton getInstance() {
        if (instance != null) {
            instance = new Singleton();
        }
        return instance;
    }
} 

双检索懒汉

public class Singleton {
    private static final volatile Singleton instance = null;
    private Singleton(){}
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized(Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

内部类懒汉式

public class Singleton {
    private Singleton(){};
    private static class Holder {
        static Singleton instance = new Singleton();
    }
    public static Singleton getInstance () {
        return Holder.instance;
    }
}
posted on 2022-05-26 11:19  万能包哥  阅读(24)  评论(0编辑  收藏  举报