饿汉模式
- 优点:线程安全,代码简单
- 缺点:不能延迟加载
public class Singleton { private Singleton(){} private static Singleton singleton = new Singleton(); public static Singleton getInstance(){ return singleton; } }
懒汉模式
- 版本一
- 优点:简单,延迟加载
- 缺点:线程不安全
public class Singleton { private Singleton(){} public static Singleton getInstance(){ return new Singleton(); } }
- 版本2
- 优点:代码简单;延迟加载
- 缺点:线程不安全
public class Singleton { private Singleton(){} private static Singleton singleton; public static Singleton getInstance(){ if (singleton == null) singleton = new Singleton(); return singleton; } }
- 版本3
- 优点:能延迟加载,对单线程程序无影响
- 缺点 :线程不安
public class Singleton { private Singleton(){} private static Singleton singleton = new Singleton(); public static synchronized Singleton getInstance(){ if (singleton == null) singleton = new Singleton(); return singleton; } }
- 版本4——双重检查锁定+volatile关键字
- 优点:能延迟加载,也能保证线程安全
- 缺点:代码复杂
public class Singleton { private Singleton(){} private static volatile Singleton singleton = new Singleton(); public static Singleton getInstance(){ if (singleton == null) { synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } }
延迟初始化占位符
- 优点:能延迟加载,也能保证线程安全
public class Singleton { private Singleton(){} private static class InstanceHolder{ public static final Singleton singleton = new Singleton(); } public static Singleton getInstance(){ return InstanceHolder.singleton; } }
枚举
public enum Singleton { INSTANCE; public void someMethod() { } }