Junior — Middle
Can you give an example of a situation where you applied the Singleton pattern in your practice?
sobes.tech AI
Answer from AI
The Singleton pattern is used when you need to ensure that a class has only one instance, such as for managing application configuration or database connections. In one project, we had a class ConfigManager that loaded settings from a file and needed to be accessible everywhere as a single object to avoid data desynchronization and redundant loading.
Example implementation of Singleton in Java:
public class ConfigManager {
private static ConfigManager instance;
private Properties properties;
private ConfigManager() {
properties = new Properties();
// load settings
}
public static synchronized ConfigManager getInstance() {
if (instance == null) {
instance = new ConfigManager();
}
return instance;
}
public String getProperty(String key) {
return properties.getProperty(key);
}
}