knowledge/technology/programming/patterns/creational/Singleton Pattern.md
2023-12-04 11:02:23 +01:00

3.4 KiB

obj
concept

Singleton Pattern

Description:

The 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. It is commonly used when you want to restrict the instantiation of a class to a single object and control access to that unique instance across the application.

How it's Used:

  1. Private Constructor: Ensure that the class has a private constructor to prevent direct instantiation from external code.
  2. Static Instance: Create a static instance of the class within the class itself.
  3. Lazy or Eager Initialization: Decide whether to initialize the instance lazily (on-demand) or eagerly (at the time of class loading). Lazy initialization is preferred if resource usage should be minimized.
  4. Static Method: Provide a static method within the class to access the unique instance. This method should handle the creation of the instance if it doesn't exist or return the existing instance.
  5. Thread Safety (Optional): If your application is multithreaded, ensure that the creation of the instance and access to it is thread-safe, especially if using lazy initialization.

Example:

A classic example of the Singleton Pattern is creating a configuration manager that provides access to application-wide configuration settings:

public class ConfigurationManager {
    private static ConfigurationManager instance; // Static instance variable
    private String configurationData;

    // Private constructor to prevent external instantiation
    private ConfigurationManager() {
        // Initialize configurationData from a configuration file or other source
        configurationData = "Default configuration";
    }

    // Static method to provide access to the unique instance
    public static ConfigurationManager getInstance() {
        if (instance == null) {
            instance = new ConfigurationManager(); // Lazy initialization
        }
        return instance;
    }

    public String getConfigurationData() {
        return configurationData;
    }

    public void setConfigurationData(String data) {
        configurationData = data;
    }
}

In this Java example:

  • The ConfigurationManager class has a private constructor to prevent external instantiation.
  • It contains a private static instance variable.
  • The getInstance static method is used to access the unique instance of the class. It initializes the instance lazily when called for the first time.
  • You can use ConfigurationManager.getInstance() to access the configuration manager from anywhere in your application.
public class Main {
    public static void main(String[] args) {
        ConfigurationManager configManager1 = ConfigurationManager.getInstance();
        ConfigurationManager configManager2 = ConfigurationManager.getInstance();

        // Both instances refer to the same unique object
        System.out.println(configManager1 == configManager2); // true

        // Access and modify configuration data
        System.out.println(configManager1.getConfigurationData()); // Default configuration
        configManager1.setConfigurationData("New configuration");
        System.out.println(configManager2.getConfigurationData()); // New configuration
    }
}

The Singleton Pattern ensures that there's only one instance of ConfigurationManager throughout the application, providing a centralized and controlled way to manage configuration data.