본문 바로가기
Python Design Patterns

The Singleton Pattern

by 자동매매 2023. 3. 29.

pattern

 

이 패턴은 클래스의 인스턴스화를 하나의 객체로 제한합니다. 

생성 패턴의 한 유형이며 메서드와 지정된 개체를 생성하는 데 하나의 클래스만 포함됩니다.

생성된 인스턴스에 대한 글로벌 액세스 지점을 제공합니다.

 

 

class Singleton:
   __instance = None
   
   def __init__(self):
      """ Virtually private constructor. """
      if Singleton.__instance != None:
         raise Exception("This class is a singleton!")
      else:
         Singleton.__instance = self   

   @staticmethod
   def getInstance():
      """ Static access method. """
      if Singleton.__instance == None:
         Singleton()
      return Singleton.__instance

if __name__ == "__main__":
    try:    
        s = Singleton()
        print (s)
        s = Singleton()
    except Exception as e:
        print(e)

    s = Singleton.getInstance()
    print (s)

    s = Singleton.getInstance()
    print (s)

 

설명

 

result

 

<__main__.Singleton object at 0x0000020ECD4B2A70>
This class is a singleton!
<__main__.Singleton object at 0x0000020ECD4B2A70>
<__main__.Singleton object at 0x0000020ECD4B2A70>

 

source code

singletone.py
0.00MB

'Python Design Patterns' 카테고리의 다른 글

Initialization and Cleanup  (0) 2023.03.31

댓글