中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

java單例模式怎么實現

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

Java中單例模式的實現方法有以下幾種:

  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. 靜態內部類:
public class Singleton {
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton() {}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}

以上是幾種常見的單例模式實現方法,每種方法都有各自的優缺點,可以根據具體需求選擇適合的實現方法。

0
沂水县| 拉萨市| 牙克石市| 久治县| 桦川县| 嘉善县| 铁岭市| 兴安盟| 都安| 冕宁县| 德清县| 潞西市| 普陀区| 伽师县| 通化市| 临夏市| 祁门县| 武穴市| 藁城市| 满城县| 天水市| 菏泽市| 县级市| 潜江市| 连平县| 龙山县| 揭阳市| 十堰市| 茶陵县| 麻城市| 南靖县| 怀来县| 怀仁县| 酒泉市| 南漳县| 壶关县| 易门县| 宁安市| 美姑县| 阜宁县| 左贡县|