class Singleton(object):
def __new__(cls, *args, **kwargs):
if not hasattr(cls, 'instance'):
cls.instance = super(Singleton, cls).__new__(cls)
return cls.instance
s = Singleton()
print("Object created1", s)
s1 = Singleton()
print("Object created2", s1)
....
('Object created1', <__main__.Singleton object at 0x10d8b05d0>)
('Object created2', <__main__.Singleton object at 0x10d8b05d0>)
class Singleton:
__instance = None
def __init__(self):
if not Singleton.__instance:
print("__init__ method called")
else:
print("Instance already crated:", self.getInstance())
@classmethod
def getInstance(cls):
if not cls.__instance:
cls.__instance = Singleton()
return cls.__instance
s = Singleton()
print("Object created", Singleton.getInstance())
s1 = Singleton()
....
__init__ method called
__init__ method called
('Object created', <__main__.Singleton instance at 0x1092b93b0>)
('Instance already crated:', <__main__.Singleton instance at 0x1092b93b0>)
객체는 다르지만 상태값은 공유한다.
class Borg:
__shared_state = {"1": "2"}
def __init__(self):
self.x = 1
self.__dict__ = self.__shared_state
pass
b = Borg()
b1 = Borg()
b.x = 4
print("Borg Object 'b': ", b)
print("Borg Object 'b1': ", b1)
print("Object State 'b", b.__dict__)
print("Object State 'b1", b1.__dict__)