MulaiMulai sekarang secara gratis

Implementing the Singleton pattern

Your application needs to manage logging configurations across multiple components. Each component currently creates its own LogManager, causing configuration inconsistencies. You need to finish the implementation of the singleton pattern to ensure all components share the same logging configuration.

Latihan ini adalah bagian dari kursus

Optimizing Code in Java

Lihat Kursus

Petunjuk latihan

  • Add a static variable called instance of type LogManager.
  • Make the constructor accessible only from within the class.
  • Only create a LogManager instance if is it currently null.

Latihan interaktif praktis

Cobalah latihan ini dengan menyelesaikan kode contoh berikut.

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;
    }
}
Edit dan Jalankan Kode