java 设计模式 —— 浅析单例模式

来源:互联网 发布:开淘宝企业店需要什么 编辑:程序博客网 时间:2024/06/16 06:12
  • 饿汉模式
  • 懒汉模式
  • Double Check Lock
  • 静态内部类

推荐:
静态内部类优先

饿汉模式

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

优点:线程安全,final 关键字确保实例在初始化后不会再被改变
缺点:为什么叫饿汉模式?因为在 final static 关键字确保类加载的同时就已经创建好了实例,而并不是我们需要的时候再来创建,可能会有些浪费资源。

懒汉模式

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

优点:线程安全,且需要对象时才实例化对象
缺点:每次获取对象都要同步,耗时

Double Check Lock

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

优点:线程安全,需要时才初始化对象
缺点:由于 Java 内存模型的原因可能会加载失败,虽然概率很小,故推荐在实例对象前加上 volatile 关键字,即 private static volatile Singleton instance

静态内部类

public class Singleton {    private Singleton {}    public static Singleton getInstance() {        return SingletonHolder.instance;    }    private static class SingletonHolder{        private static final Singleton instance = new Singleton();    }}

优点:线程安全,延迟加载

0 0