Python Singleton
The Singleton pattern is a commonly used software design pattern that ensures a class has only one instance and provides a global access point to get that instance.\\\\n\\\\n### Core Concepts\\\\n\\\\nImagine the CEO position in a company - there can only be one CEO in the entire company, and no matter which department needs to report to the CEO, they all access the same CEO object. The Singleton pattern is the "CEO position management mechanism" in the programming world.\\\\n\\\\n### Why We Need the Singleton Pattern\\\\n\\\\nIn actual development, there are some objects for which we only need one instance, such as:\\\\n\\\\n* **Configuration Manager**: The entire application shares the same set of configurations\\\\n* **Database Connection Pool**: Avoids creating duplicate connections, saving resources\\\\n* **Logger**: Ensures all logs are written to the same file\\\\n* **Cache System**: Centrally manages cached data\\\\n\\\\n* * *\\\\n\\\\n## Implementation Methods of the Singleton Pattern\\\\n\\\\nPython provides multiple ways to implement the Singleton pattern. Let's explore them one by one, from simple to complex.\\\\n\\\\n### Method 1: Using Modules (The Simplest Way)\\\\n\\\\nPython modules themselves are naturally singletons. When a module is imported, it is initialized once, and subsequent imports will all use the same instance.\\\\n\\\\n## Instance\\\\n\\\\n```python\\\\n# singleton_module.py\\\\n\\\\nclass DatabaseConnection:\\\\n\\\\n def __init__(self):\\\\n self.connection_string = "database://localhost:5432/mydb"\\\\n print("Database connection created")\\\\n\\\\n def query(self, sql):\\\\n return f"Execute query: {sql}"\\\\n\\\\n# createSingleton Instance\\\\ndb_instance = DatabaseConnection()\\\\n\\\\n# Use in other files:\\\\n# from singleton_module import db_instance\\\\n# result = db_instance.query("SELECT * FROM users")\\\\n```\\\\n\\\\n### Method 2: Using the `__new__` Method\\\\n\\\\nControl the instance creation process by overriding the `__new__` method.\\\\n\\\\n## Instance\\\\n\\\\n```python\\\\nclass Singleton:\\\\n _instance = None\\\\n\\\\n def __new__(cls, *args, **kwargs):\\\\n # If Instance does not exist, then create new Instance\\\\n if not cls._instance:\\\\n cls._instance = super().__new__(cls)\\\\n print("createnew'sSingleton Instance")\\\\n else:\\\\n print("Returns existing'sSingleton Instance")\\\\n return cls._instance\\\\n\\\\n def __init__(self, name):\\\\n # Note: __init__ will be called every time\\\\n self.name = name\\\\n print(f"Initialized instance, Name: {name}")\\\\n\\\\n# Test code\\\\nprint("=== Test singleton pattern ===")\\\\ns1 = Singleton("First Instance")\\\\ns2 = Singleton("Second instance")\\\\nprint(f"s1 's ID: {id(s1)}")\\\\nprint(f"s2 's ID: {id(s2)}")\\\\nprint(f"s1 and s2 Is it the same object? {s1 is s2}")\\\\nprint(f"s1 Name: {s1.name}")\\\\nprint(f"s2 Name: {s2.name}") # Note: This will be displayed here"Second instance"\\\\n```\\\\n\\\\n**Output:**\\\\n\\\\n```\\\\n=== Test singleton pattern ===createnew'sSingleton Instance initialized instance, Name: First Instance returns existing'sSingleton Instance initialized instance, Name: Second instance s1 's ID: 140245678945600 s2 's ID: 140245678945600 s1 and s2 Is it the same object? True s1 Name: Second instance s2 Name: Second instance\\\\n```\\\\n\\\\n### Method 3: Using Decorators\\\\n\\\\nCreate a universal singleton decorator that can easily convert any class into a singleton.\\\\n\\\\n## Instance\\\\n\\\\n```python\\\\ndef singleton(cls):\\\\n """Singleton decorator"""\\\\n instances = {}\\\\n\\\\n def get_instance(*args, **kwargs):\\\\n # If the class has no Instance yet, then create new Instance\\\\n if cls not in instances:\\\\n instances = cls(*args, **kwargs)\\\\n print(f"create {cls.__name__} 'sNew Instance")\\\\n else:\\\\n print(f"Returns existing's {cls.__name__} Instance")\\\\n return instances\\\\n\\\\n return get_instance\\\\n\\\\n@singleton\\\\nclass ConfigurationManager:\\\\n def __ini
YouTip