懒汉式(线程不安全)
1 2 3 4 5 6 7 8 9 10 11 12 13
| public class Singleton { private static Singleton instance = null; private Singleton() { } public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
|
懒汉式(线程安全)
1 2 3 4 5 6 7 8 9 10 11 12 13
| public class Singleton { private static Singleton instance = null; private Singleton() { } public static synchronized Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
|
饿汉式(线程安全)
1 2 3 4 5 6 7 8 9 10
| public class Singleton { private static Singleton instance = new Singleton(); private Singleton() { } public static Singleton getInstance() { return instance; } }
|
双重校验锁(线程安全,懒加载,JDK 1.5 以上)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| public class Singleton { private volatile static Singleton instance = null; private Singleton() { } public static Singleton getInstance() { if (instance == null) { synchronized(Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } }
|
静态内部类(线程安全,懒加载)
1 2 3 4 5 6 7 8 9 10 11 12
| public class Singleton { private Singleton() { } public static Singleton getInstance() { return SingletonHolder.instance; }
private static class SingletonHolder { private static Singleton instance = new Singleton(); } }
|
上面列出的是常用的几种,还有其它方式来构建单例,比如使用枚举或容器类来构建,但我很少用到,便不再列出,需要的可自行搜索。