Singleton pattern is a creational design pattern that ensures a class has only one instance and provides a global point of access to that instance. The instance is encapsulated within the singleton class and enables strict control over how clients access it.

Applicability

  • When you need to provide global access to a single instance of a class, but also need to control the instantiation of that class to ensure that only one instance is created. (e.g. configuration manager, your app needs to read configuration once and keep them in memory for later fast access)
  • When you want centralised management of resources, and sharing the resources to multiple parts of your system. Singleton ensures that all parts of the system are interacting with the same resource instance to secure data integrity.
  • When you want to control the access to a resource or feature, preventing multiple instances to be created.

Approach

  1. Create the singleton class, the class maintains a private static singleton instance.
  2. The singleton class has a private constructor that ensures only the class itself can instantiate and manage only one singleton instance to exist.
  3. Provide a public static method for client to access the singleton instance.
  4. (Optional) Make the singleton thread-safe to prevent multiple threads from creating multiple singleton instances.

Components

  • Singleton
    • Maintains a singleton object as as its private field
    • Defines a getInstance() operation for clients to access its unique instance
    • May be responsible for creating its own unique instance

Example

This example uses singleton pattern for reading configuration.

Singleton class

public class ConfigurationReader {
    private static ConfigurationReader instance;
    private Properties properties;
 
    private ConfigurationReader(String configPath) {
        loadProperties(configPath);
    }
 
    public static ConfigurationReader getInstance() {
	    // only create the singleton instance if it hasn't already been created
        if (instance == null) {
			instance = new ConfigurationReader();
        }
        return instance;
    }
 
    private void loadProperties(String configPath) {
        properties = new Properties();
		// your code for reading configuration here
    }
 
    public String getProperty(String key) {
        return properties.getProperty(key);
    }
}

Client

ConfigurationReader config = ConfigurationReader.getInstance("setting.config");
 
String systemInfo = config.getProperty("database.password");
System.out.println(systemInfo);

In this example the ConfigurationReader is a singleton class that loads the configuration and stores in the properties object. When any client wants to retrieve the configuration, the client calls the getInstance method of the singleton class, and later use the singleton instance for specific purposes.


Back to parent node: Creational Patterns

Design_PatternCreational_Design_PatternsSOFT2201Singleton_pattern