一.單件模式通常實現
二.單件模式多線程實現
一.單件模式通常實現java
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 synchronized static Singleton getInstance() { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } return uniqueInstance; } }
問題:性能下降性能
A. 如何getInstance()的性能對應用程序不是關鍵,就什麼都不要作.同步可能使應用程序的執行效率下降100倍,但若是此方法不是被頻繁的調用,則不用修改.由於同步的getInstance()方法既簡單又有效.線程
B.使用"急切"建立實例,而不用延遲化的實例的方法code
public class Singleton { private static Singleton uniqueInstance = new Singleton(); public synchronized Singleton getInstance() { return uniqueInstance; } }
C.使用"雙重檢查加鎖",儘可能減小使用同步:若是性能是你關心的,此方法可大大減小時間消耗get
public class Singleton { private static volatile Singleton uniqueInstance; public static Singleton getInstance() { if (uniqueInstance == null) { synchronized (Singleton.class) { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } } } return uniqueInstance; } }