싱글톤 디자인 패턴

런던행·2020년 8월 3일
0

디자인 패턴

목록 보기
2/8

싱글톤 디자인 패턴의 목적

  • 클래스에 대한 단일 객체 생성
  • 전역 객체 제공
  • 공유된 리소스에 대한 동시 접근제어

파이썬 싱글톤 패턴 구현

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>)

게으른 초기화(Lazy instantiation)

  • 게으른 초기화는 인스턴스가 꼭 필요할 때 생성

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__)
profile
unit test, tdd, bdd, laravel, django, android native, vuejs, react, embedded linux, typescript

0개의 댓글