Singleton Pattern
Ensuring single instance
Interview Relevant: Design patterns
Singleton Pattern
Ensure a class has only one instance.
Code Examples
Implementation using __new__.
python
1class Singleton:
2 _instance = None
3 def __new__(cls):
4 if cls._instance is None:
5 cls._instance = super().__new__(cls)
6 return cls._instance
7
8s1 = Singleton()
9s2 = Singleton()
10print(s1 is s2) # True