单件模式确保一个类只有一个实例,并提供一个全局访问点。安全
要点:线程
延迟建立单件实例。code
线程不安全:get
/** * 单件类(懒汉式、线程不安全) */ public class Singleton { /** * 惟一单件实例 */ private static Singleton uniqueInstance; /** * 私有构造 */ private Singleton() {} /** * 获取单件实例 */ public static Singleton getInstance() { if (uniqueInstance == null) { // 延迟建立单件实例 uniqueInstance = new Singleton(); } return uniqueInstance; } }
线程安全:同步
/** * 单件类(懒汉式、线程安全) */ public class Singleton { /** * 惟一单件实例 */ private static Singleton uniqueInstance; /** * 私有构造 */ private Singleton() {} /** * 获取单件实例(同步方法) */ public static synchronized Singleton getInstance() { if (uniqueInstance == null) { // 延迟建立单件实例 uniqueInstance = new Singleton(); } return uniqueInstance; } }
“急切”建立单件实例。class
/** * 单件类(饿汉式) */ public class Singleton { /** * 惟一单件实例(“急切”建立单件实例) */ private static Singleton uniqueInstance = new Singleton(); /** * 私有构造 */ private Singleton() {} /** * 获取单件实例 */ public static Singleton getInstance() { return uniqueInstance; } }
/** * 单件类(双重检查加锁) */ public class Singleton { /** * 惟一单件实例 */ private volatile static Singleton uniqueInstance; /** * 私有构造 */ private Singleton() {} /** * 获取单件实例 */ public static Singleton getInstance() { if (uniqueInstance == null) { synchronized (Singleton.class) { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } } } return uniqueInstance; } }
public class Test { public static void main(String[] args) { // 获取单件实例 Singleton singleton = Singleton.getInstance(); System.out.println(singleton); Singleton singleton2 = Singleton.getInstance(); System.out.println(singleton2); } }