在Java中,實現(xiàn)單例模式主要有幾種方式:懶漢式、餓漢式、雙重檢查鎖定、靜態(tài)內(nèi)部類和枚舉。每種方式都有其特點和適用場景。
1. 餓漢式(線程安全)
餓漢式是最簡單的一種實現(xiàn)方式,通過靜態(tài)初始化實例,保證了線程安全。但它不是懶加載模式,無法在實際使用時才創(chuàng)建實例。
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
2. 懶漢式(線程不安全)
懶漢式實現(xiàn)了懶加載,但在多線程情況下不能保證單例的唯一性。
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
3. 懶漢式(線程安全)
通過同步方法保證線程安全,但每次訪問時都需要同步,會影響性能。
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
4. 雙重檢查鎖定(DCL)
雙重檢查鎖定既保證了線程安全,又避免了每次訪問時的性能損失。
public class Singleton {
private volatile static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
5. 靜態(tài)內(nèi)部類
使用靜態(tài)內(nèi)部類的方式實現(xiàn)懶加載,且由JVM保證線程安全。文章來源:http://www.zghlxwxcb.cn/news/detail-828844.html
public class Singleton {
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton() {}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
6. 枚舉
使用枚舉的方式是實現(xiàn)單例的最佳方法,不僅能避免多線程同步問題,還能防止反序列化重新創(chuàng)建新的對象。文章來源地址http://www.zghlxwxcb.cn/news/detail-828844.html
// 實現(xiàn)枚舉單例
public enum Singleton {
INSTANCE; // 唯一的枚舉實例
// 枚舉類中可以包含成員變量、方法等
private int value;
// 可以定義自己需要的操作,如設(shè)置、獲取枚舉實例的狀態(tài)等
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
// 還可以定義其他方法
public void show() {
System.out.println("This is an enum singleton method.");
}
}
// 使用枚舉單例
public class TestSingleton {
public static void main(String[] args) {
Singleton singleton = Singleton.INSTANCE;
singleton.setValue(1);
System.out.println(singleton.getValue());
singleton.show();
}
}
到了這里,關(guān)于單例模式的幾種實現(xiàn)方式的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!