Singleton¶
Wzorzec ten wymusza istnienie tylko jednego obiektu danej klasy. Jeżeli nie stworzono ani jednego, wywoływany jest konstruktor. W przeciwnym przypadku zwracana jest referencja do tego jedynego, który już istnieje:
1class Singleton :
2
3 __instance = None
4
5 @staticmethod
6 def get_instance():
7
8 """ Static access method. """
9 if Singleton.__instance == None:
10 Singleton()
11 return Singleton.__instance
12
13 def __init__(self) :
14 if Singleton.__instance == None :
15 Singleton.__instance = self
16 else :
17 raise Exception("This class is a singleton!")
18
19s = Singleton()
20print(s)
21
22s = Singleton.get_instance()
23print(s)
24
25s = Singleton()
26print(s)
Powtórne wywołanie konstruktora powoduje podniesienie wyjątku. W prawdziwie obiektowych językach jak Java albo C++ możliwe jest zadeklarowanie konstruktora jako prywatnej składowej klasy. Wtedy to jedynie metoda get_instance() jest wstanie wywołać konstruktor.