單例模式確保某個類別在整個系統中僅有一個實例,並自行實例化且提供全域存取點。適用於建立物件資源消耗大、需頻繁建立銷毀、或需共享資源(如資料庫連線、執行緒池、配置管理)的場景。
包含兩個角色:Client(高層客戶端)與 Singleton(單例類別)。Singleton 提供私有建構子、靜態實例變數與公開的 getInstance() 方法。
public class Singleton {
private static volatile Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
public class Singleton1 {
private static final Singleton1 INSTANCE = new Singleton1();
private Singleton1() {}
public static Singleton1 getInstance() { return INSTANCE; }
}
public class Singleton2 {
private static Singleton2 instance;
private Singleton2() {}
public static Singleton2 getInstance() {
if (instance == null) instance = new Singleton2();
return instance;
}
}
public class Singleton3 {
private static Singleton3 instance;
private Singleton3() {}
public synchronized static Singleton3 getInstance() {
if (instance == null) instance = new Singleton3();
return instance;
}
}
public class Singleton4 {
private static Singleton4 instance;
private Singleton4() {}
public static Singleton4 getInstance() {
synchronized (Singleton4.class) {
if (instance == null) instance = new Singleton4();
}
return instance;
}
}