单例模式的五种写法(Java)
最后一次更新时间:Friday, January 22nd 2021, PM
饿汉式
| public class Singleton{ private static Singleton instance = new Singleton(); private Singleton(){} public static Singleton getInstance(){ return instance; } }
|
懒汉式(线程不安全)
| public class Singleton{ private static Singleton instace; private Singleton(){}
public static Singleton getInstance(){ if (instance == null){ instance = new Singleton(); } return instace; } }
|
懒汉式(线程安全)
效率低,每次都要加锁
| public class Singleton{ private static Singleton instace; private Singleton(){}
public static synchronized Singleton getInstance(){ if (instance == null){ instance = new Singleton(); } return instace; } }
|
双重校验锁 DCL(Double Checked Locking)
先判断,若对象已创建,则不进入synchronized代码块。提升了性能且保证安全。
Volate一般用于保证多线程可见性。这里用来防止指令重排序。
| public class Singleton{ private volatile static Singleton instance; private Singleton(){}; public static Singleton getInstance(){ if (instance == null){ synchronized(Singleton.class){ if (instance == null){ instance = new Singleton(); } } } return instance; } }
|
静态内部类
调用getInstance()才初始化,更加灵活。
| public class Singleton{ private static class SingletonHolder{ private static final Singleton INSTANCE = new Singleton(); } private Singleton(){} public static final Singleton getInstance(){ return SingletonHolder.INSTANCE; } }
|