Java實現(xiàn)單例模式的五種方式總結(jié)
更新時間:2025年01月06日 09:22:39 作者:今天不coding
這篇文章主要介紹了如何實現(xiàn)一個單例模式,包括構(gòu)造器私有化、提供靜態(tài)私有變量和公共獲取實例接口,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
如何實現(xiàn)一個單例
1、構(gòu)造器需要私有化
2、提供一個私有的靜態(tài)變量
3、暴露一個公共的獲取單例對象的接口
需要考慮的兩個問題
1、是否支持懶加載
2、是否線程安全
1、餓漢式
public class EagerSingleton {
private static final EagerSingleton INSTANCE = new EagerSingleton();
private EagerSingleton(){}
public EagerSingleton getInstance(){
return INSTANCE;
}
}
不支持懶加載
線程安全
2、懶漢式
public class LazySingleton {
private static LazySingleton INSTANCE;
private LazySingleton() {
}
public static LazySingleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new LazySingleton();
}
return INSTANCE;
}
}
支持懶加載
線程不安全
public class LazySingleton {
private static LazySingleton INSTANCE;
private LazySingleton() {
}
public static synchronized LazySingleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new LazySingleton();
}
return INSTANCE;
}
}
支持懶加載
線程安全
3、雙重檢查鎖
public class DoubleCheckSingleton {
private static DoubleCheckSingleton INSTANCE;
private DoubleCheckSingleton() {
}
public DoubleCheckSingleton getInstance() {
if (INSTANCE == null) {
synchronized (DoubleCheckSingleton.class) {
if (INSTANCE == null) {
INSTANCE = new DoubleCheckSingleton();
}
}
}
return INSTANCE;
}
}
支持懶加載
線程安全
4、靜態(tài)內(nèi)部類
public class InnerSingleton {
private InnerSingleton() {
}
public static InnerSingleton getInstance() {
return Singleton.INSTANCE;
}
private static class Singleton {
private static final InnerSingleton INSTANCE = new InnerSingleton();
}
}
支持懶加載
線程安全
5、枚舉
public enum EnumSingleton {
INSTANCE;
}總結(jié)
到此這篇關(guān)于Java實現(xiàn)單例模式的五種方式的文章就介紹到這了,更多相關(guān)Java實現(xiàn)單例模式方式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
mybatis使用case when按照條件進(jìn)行更新方式
示例一通過條碼批量更新入庫和剩余數(shù)量,直接高效;示例二使用set和trim標(biāo)簽,實現(xiàn)動態(tài)字段更新與條件優(yōu)化,結(jié)構(gòu)更復(fù)雜但靈活性更高2025-07-07
Mybatis千萬級數(shù)據(jù)查詢的解決方式,避免OOM問題
這篇文章主要介紹了Mybatis千萬級數(shù)據(jù)查詢的解決方式,避免OOM問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01
SpringBoot設(shè)置默認(rèn)主頁的方法步驟
這篇文章主要介紹了SpringBoot設(shè)置默認(rèn)主頁的方法步驟,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12

