Created
March 6, 2012 19:47
-
-
Save ptigas/1988605 to your computer and use it in GitHub Desktop.
example of singleton design pattern in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
counter = 1 | |
class TestSingleton: | |
__instance = None | |
__var = 0 | |
def __init__(self): | |
global counter | |
self.__var = counter | |
counter += 1 | |
def get_var(self): | |
return self.__var | |
@staticmethod | |
def get_instance(): | |
if TestSingleton.__instance == None : | |
TestSingleton.__instance = TestSingleton() | |
return TestSingleton.__instance | |
t1 = TestSingleton.get_instance() | |
print id(t1), t1.get_var() | |
t2 = TestSingleton.get_instance() | |
print id(t2), t2.get_var() | |
t3 = TestSingleton.get_instance() | |
print id(t3), t3.get_var() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment