Singleton is a creational design pattern that lets you ensure that a class has only one instance while providing a global access point to this instance.

Singleton class ensures that a class has just a single instance. Here is how it works: imagine that you created an object, but after a while decided to create anew one. Instead of receiving a fresh object, you will get the one you already created.

Why would anyone want to control how many instances a class has? The most common reason for this is to control access to some shared resource Example: a database or a file.

Singleton class provides a global access point to that instance. The singleton pattern allows you to access some object from anywhere in the program. However, it also protects that instance from being overwritten by other code.

Example:

Implement a configuration manager using the singleton design pattern. The configuration manager should read configuration settings from a file and provide access to these settings throughout the application. Demonstrate how the single design pattern ensures that there is only one instance of the configuration manager, preventing unnecessary multiple reads of the configuration files.

import json


class ConfigurationManager(object):
def __init__(self, config_file) -> None:
self.config_file = config_file
self.configurations = self.load_config()

def __new__(self, config_file):
"""
create new instance if there are no other instance, else return the current instance
"""
if not hasattr(self, "instance"):
self.instance = super(ConfigurationManager, self).__new__(self)
return self.instance

def load_config(self):
with open(self.config_file, "r") as file:
return json.load(file)

def get_config(self):
return self.configurations


config_file = "config.json"
configuration_manager_1 = ConfigurationManager(config_file)
configuration_manager_2 = ConfigurationManager(config_file)
print(configuration_manager_1 is configuration_manager_2)

config = configuration_manager_1.get_config()
print(type(config))
print(config)