In Python, there are many ways to implement a singleton pattern, each with its advantages and disadvantages. Let’s first make the conclusion. If you are interested in a certain implementation method, you can read it selectively.
1. Conclusion
Implementation method | advantage | shortcoming | Recommended words |
---|---|---|---|
Metaclass | Thread safe, flexible | Implementation complex | Suitable for scenarios where flexibility and thread safety are required |
|
Thread safe, simple implementation | Need to use thread lock | Suitable for scenarios that require simple implementation |
Module | Simple and easy to use, thread-safe | Unable to create singleton instance dynamically | Want to be simple and able to receive static singleton scenarios |
importlib |
Flexible, dynamically loading singleton instances | Requires additional module support | Not recommended |
__new__ method |
Simple and intuitive | Non-thread safe | Not recommended |
Decorators | Flexible, applicable to multiple classes | Non-thread safe | Not recommended |
2. Use metaclasses
2.1 Implementation method
Control the class creation process through custom metaclasses to ensure that the class creates only one instance.
2.2 Sample code
class SingletonMeta(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(SingletonMeta, cls).__call__(*args, **kwargs) return cls._instances[cls] class Singleton(metaclass=SingletonMeta): def __init__(self, value): = value # tests1 = Singleton(10) s2 = Singleton(20) print() # Output: 10print() # Output: 10print(s1 is s2) # Output: True
2.3 Advantages
- Thread-safe, suitable for multi-threaded environments.
- Flexible, can be applied to multiple classes.
2.4 Disadvantages
- The implementation is relatively complex and difficult to understand.
3. Use a single case to achieve thread safety
3.1 Implementation method
passMake sure to create only one instance in a multi-threaded environment.
3.2 Sample code
import threading class Singleton: _instance = None _lock = () def __new__(cls, *args, **kwargs): if not cls._instance: with cls._lock: if not cls._instance: cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs) return cls._instance # tests1 = Singleton() s2 = Singleton() print(s1 is s2) # Output: True
3.3 Advantages
- Thread-safe, suitable for multi-threaded environments.
3.4 Disadvantages
- The implementation is slightly more complicated.
4. Use modules
4.1 Implementation method
In Python, modules are natural singletons. Because the module will be initialized during the first import, the instance that has been initialized will be used during subsequent imports.
4.2 Sample code
# singleton_module.py class Singleton: def __init__(self): = "Singleton Instance" instance = Singleton() # Import in other filesfrom singleton_module import instance print() # Output: Singleton Instance
4.3 Advantages
- Simple and easy to use, native Python support.
- Thread-safe, no additional processing required.
4.4 Disadvantages
- Unable to create singleton instances dynamically.
5. Use the importlib module
5.1 Implementation method
passimportlib
Modules are dynamically imported into modules to ensure that the module is imported only once.
5.2 Sample Code
import importlib class Singleton: _instance = None @staticmethod def get_instance(): if Singleton._instance is None: Singleton._instance = importlib.import_module("singleton_module").instance return Singleton._instance # tests1 = Singleton.get_instance() s2 = Singleton.get_instance() print(s1 is s2) # Output: True
5.3 Advantages
- Flexible, dynamically loading singleton instances.
5.4 Disadvantages
- Additional module support is required.
6. Use the __new__ method
6.1 Implementation method
By rewriting the class__new__
Method, ensure that the class returns only the same instance when creating an instance.
6.2 Sample Code
class Singleton: _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs) return cls._instance # tests1 = Singleton() s2 = Singleton() print(s1 is s2) # Output: True
6.3 Advantages
- Simple and intuitive, easy to understand.
6.4 Disadvantages
- Non-threaded safety, multiple instances may be created in a multi-threaded environment.
7. Use a decorator
7.1 Implementation method
Convert class to singleton class via decorator.
7.2 Sample Code
def singleton(cls): instances = {} def get_instance(*args, **kwargs): if cls not in instances: instances[cls] = cls(*args, **kwargs) return instances[cls] return get_instance @singleton class MyClass: def __init__(self, value): = value # testm1 = MyClass(10) m2 = MyClass(20) print() # Output: 10print() # Output: 10print(m1 is m2) # Output: True
7.3 Advantages
- Flexible, can be applied to multiple classes.
7.4 Disadvantages
- Non-threaded safety, multiple instances may be created in a multi-threaded environment.
This is the end of this article about the implementation example of Python using singleton pattern to create classes. For more related content on Python singleton pattern creation, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!