certain-design-patterns/singleton.py

22 lines
955 B
Python
Raw Permalink Normal View History

2025-02-07 12:10:20 +03:00
class Singleton:
__instance = None
def __init__(self):
if not Singleton.__instance:
print("init method is called")
else:
print("instance is already created:", self.getInstance())
@classmethod
# cls — это конвенция, аналогичная self, но вместо ссылки на экземпляр класса (как в обычных методах),
# она ссылается на сам класс. Это позволяет вам обращаться к атрибутам и методам
# класса без необходимости создавать экземпляр класса.
def getInstance(cls):
if not cls.__instance:
cls.__instance = Singleton()
return cls.__instance
singleton1 = Singleton.getInstance()
singleton2 = Singleton.getInstance()
print("singleton1:", singleton1)
print("singleton2:", singleton2)