- 單例模式用于限制一個類的對象個數(shù),確保在JVM中只有一個類的對象畅铭。通常用于在應(yīng)用程序中只有需要有一個全局對象的情形下蹬敲。
- 比如:Singleton pattern is used for logging, drivers objects, caching and thread pool
- Singleton design pattern is used in core java classes also, for example java.lang.Runtime
,java.awt.Desktop.
單例模式的實現(xiàn)方法:
單例模式有不同的實現(xiàn)方法,但都遵循以下的步驟:
- 將構(gòu)造方法私有化搭盾,防止其他類使用挖垛。
- private static的該類的唯一對象痒钝。
- 提供一個public static 的getInstance()方法供外界調(diào)用秉颗。
大致就是以上的三個步驟,但是會根據(jù)對象實例化方式的不同而產(chǎn)生不同單例模式的實現(xiàn)方式送矩。
單例模式的不同實現(xiàn)方法:
Eager initialization
package com.journaldev.singleton;
public class EagerInitializedSingleton {
private static final EagerInitializedSingleton instance = new EagerInitializedSingleton();
//private constructor to avoid client applications to use constructor
private EagerInitializedSingleton(){}
public static EagerInitializedSingleton getInstance(){
return instance;
}
}
優(yōu)缺點:
--這是一種很簡單的實現(xiàn)方法蚕甥,當(dāng)class被編譯的時候,該對象就已經(jīng)產(chǎn)生
-- 通過代碼可以看出栋荸,這種實現(xiàn)的方式:在客戶端調(diào)用之前已經(jīng)對單例對象進(jìn)行了實例化的操作菇怀。所以如果客戶端應(yīng)用不需要該對象的話那么就產(chǎn)生了一種浪費。
--所以晌块,當(dāng)我們使用單例的時候不需要操作很多資源的話爱沟,那么可以推薦使用這一種簡單的創(chuàng)建方式。但是通常情況下匆背,我們創(chuàng)建單例會使用系統(tǒng)的資源和文件呼伸,比如: File System, Database connections,此時我們應(yīng)該選擇在調(diào)用時才創(chuàng)建對象的單例模式。
Lazy Initialization##
package com.journaldev.singleton;
public class LazyInitializedSingleton {
private static LazyInitializedSingleton instance;
private LazyInitializedSingleton(){}
public static LazyInitializedSingleton getInstance(){
if(instance == null){
instance = new LazyInitializedSingleton();
}
return instance;
}
}
- 這種模式的創(chuàng)建:知道客戶端需要該對象的時候才會第一次被創(chuàng)建
- 這種模式在單線程之下是安全的钝尸,但是當(dāng)多線程的時候括享,多個線程同時對其 進(jìn)行讀寫操作會可能會產(chǎn)生錯誤。
Thread Safe Singleton##
The easier way to create a thread-safe singleton class is to make the global access method synchronized, so that only one thread can execute this method at a time. General implementation of this approach is like the below class.
package com.journaldev.singleton;
public class ThreadSafeSingleton {
private static ThreadSafeSingleton instance;
private ThreadSafeSingleton(){}
public static synchronized ThreadSafeSingleton getInstance(){
if(instance == null){
instance = new ThreadSafeSingleton();
}
return instance;
}
}
--線程安全的單例模式比較簡單的實現(xiàn)是對getInstance方法加上synchronized加上鎖珍促,使得一次只能被同一線程訪問铃辖。