Singleton pattern in python
Context
python 레포 피쳐 개발하다가, 너무 오랜만에 이 개념을 봐서 복습.
What I Learned
The Singleton Pattern ensures a class has only one instance throughout a program and provides a global access point.
It is commonly used for managing shared resources like databases, logging systems or file managers.
All Python modules are singletons by default. Any variables or functions defined in a module are shared across imports.
Code
class Single:
instance = None
def __new__(cls):
if cls.instance is None:
cls.instance = super().__new__(cls)
return cls.instance
a = Single()
b = Single()
print(a is b)
Note
put the definition to the name and try not to forget