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.
This exercise is part of the course
Optimizing Code in Java
Exercise instructions
- Add a
static
variable calledinstance
of typeLogManager
. - Make the constructor accessible only from within the class.
- Only create a
LogManager
instance if is it currently null.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
import java.util.Map;
import java.util.HashMap;
public class Main {
public static void main(String[] args) {}
}
class LogManager {
// Add static instance variable to hold the instance
private ___;
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;
}
}