實作 Singleton 模式
你的應用程式需要在多個元件之間統一管理記錄(logging)設定。現在每個元件都會各自建立一個 LogManager,導致設定不一致。你需要完成 Singleton 模式的實作,確保所有元件共用相同的記錄設定。
本練習屬於課程
Java 程式碼最佳化
練習說明
- 新增一個名為
instance、型別為LogManager的static變數。 - 將建構子設為僅能在此類別內部存取。
- 只有在目前為 null 時才建立
LogManager實例。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
public class Main {
public static void main(String[] args) {}
}
class LogManager {
// Add static instance variable to hold the instance
private static ____ ____;
private Map logConfig;
// Make constructor accessible only from within the class
___ LogManager() {
logConfig = new HashMap<>();
}
public static LogManager getInstance() {
// Only create if instance is currently null
if (____ ____ ____) {
instance = new LogManager();
}
return instance;
}
}