溫馨提示×

java單例模式怎么實(shí)現(xiàn)

小億
106
2023-08-23 11:27:01
欄目: 編程語言

Java中單例模式的實(shí)現(xiàn)方法有以下幾種:

  1. 懶漢式(線程不安全):
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
  1. 懶漢式(線程安全):
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
  1. 餓漢式:
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
  1. 雙重檢查鎖定(Double-Checked Locking):
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;
}
}
  1. 靜態(tài)內(nèi)部類:
public class Singleton {
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton() {}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}

以上是幾種常見的單例模式實(shí)現(xiàn)方法,每種方法都有各自的優(yōu)缺點(diǎn),可以根據(jù)具體需求選擇適合的實(shí)現(xiàn)方法。

0