大纲:
- 5种常见单例模式
一、5种常见单例模式
1.1饿汉式
最简单是单例实现
public class Singleton { private Singleton (){ //加载配置文件.... } private static Singleton singleton = new Singleton(); public static Singleton getInstance(){ return singleton; } }
1.2懒汉式
懒汉比恶汉多了懒加载的思想
public class Singleton { private Singleton (){ //加载配置文件.... } private static Singleton singleton = null; public static Singleton getInstance(){ if(singleton==null){ singleton = new Singleton(); } return singleton; } }
1.3双检锁(DCL单例)
上面懒汉式存在线程安全问题,可以利用双重检查加锁避免。
public class Singleton { private Singleton (){ //加载配置文件.... } private volatile static Singleton singleton = null; public static Singleton getInstance(){ if(singleton==null){ synchronized (Singleton.class){ if(singleton==null){ singleton = new Singleton(); } } } return singleton; } }
1.4静态内部类
DCL这种方式解决了线程安全为题,但用了volatile,效率降低,用静态内部类可以解决这一问题。
public class Singleton { private Singleton (){ //加载配置文件.... } private static class SingletonHolder{ private static Singleton singleton = new Singleton(); } public static Singleton getInstance(){ return SingletonHolder.singleton; } }
1.5枚举
effective java推荐的一种单例模式
public enum Singleton { instance; Singleton(){ //加载配置文件.... } }