Category : Design Patterns | Sub Category : Questions on Design Patterns | By Prasad Bonam Last updated: 2023-07-12 02:31:56 Viewed : 552
Implementing a global configuration using a Singleton class in Java:
Here is an example of implementing a global configuration using a Singleton class in Java:
javaimport java.util.Properties;
public class GlobalConfiguration {
private static GlobalConfiguration instance;
private Properties properties;
private GlobalConfiguration() {
properties = new Properties();
// Load configuration properties from a file or other sources
// Example: properties.load(new FileInputStream("config.properties"));
// Set properties programmatically
properties.setProperty("key1", "value1");
properties.setProperty("key2", "value2");
}
public static synchronized GlobalConfiguration getInstance() {
if (instance == null) {
instance = new GlobalConfiguration();
}
return instance;
}
public String getProperty(String key) {
return properties.getProperty(key);
}
// Other methods for configuration management...
}
In this example, the GlobalConfiguration
class is implemented as a Singleton using a private constructor and a static getInstance()
method.
The GlobalConfiguration
class maintains a Properties
object to store configuration properties. In the constructor, you can load the properties from a file or set them programmatically as shown in the example.
The getProperty()
method allows you to retrieve a configuration property based on a given key.
To use the GlobalConfiguration
class, you can retrieve the singleton instance using GlobalConfiguration.getInstance()
and then call the getProperty()
method to access configuration properties:
javaGlobalConfiguration config = GlobalConfiguration.getInstance();
String value1 = config.getProperty("key1");
String value2 = config.getProperty("key2");
// ...
// Use the configuration properties as needed
Note that this is a basic example to illustrate the Singleton pattern and global configuration management. In a real-world scenario, you may need to handle configuration loading, validation, updating, and other aspects based on your specific requirements. Additionally, consider using configuration management frameworks such as Apache Commons Configuration or Spring Boots configuration support for more advanced configuration features and flexibility.