單例模式分爲兩種,懶漢式和餓漢式。區別在於建立實例的時機。餓漢式在該類加載時建立實例,懶漢式則在須要獲取時才進行建立。java
package Create.f.Singleton; public class Singleton { private Singleton(){ } protected static Singleton getInstance(){ System.out.println("獲取Singleton單例對象"); return instance; } private static Singleton instance = new Singleton(); //餓漢式 注意此時線程安全 }
package Create.f.Singleton; //懶漢式 public class Singleton2 { private static Singleton2 instance = null; private Singleton2(){ } protected static synchronized Singleton2 getInstance(){ if(instance == null){ System.out.println("初始化Singleton2單例對象"); instance = new Singleton2(); } return instance; } }
package Create.f.Singleton; public class Client { public static void main(String[] args) { Singleton singleton = Singleton.getInstance(); Singleton s = Singleton.getInstance(); System.out.println("是否同個對象:" + (singleton == s)); Singleton2 s2 = Singleton2.getInstance(); Singleton2 s3 = Singleton2.getInstance(); Singleton2 s4 = Singleton2.getInstance(); System.out.println("是否同個對象:" + (s2 == s3 && s3 == s4)); } }
優勢:客戶調用類的時候,只能調用一個公共的接口,提供一個共享的概念安全
缺點:在多個虛擬機下運行時,要想知道具體哪一個虛擬機運行着哪些單例是很困難的,並且可能存在着多線程安全和效率問題,此外還很難實現序列化多線程