Created
January 21, 2015 22:02
-
-
Save sujayy1983/a35b698fccc24143774f to your computer and use it in GitHub Desktop.
Singleton design pattern (Two approaches). Taken a lot of help from internet examples.
This file contains 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
""" | |
@Author: Sujayyendhiren Ramarao | |
@Description: Singleton class. More than one approach. | |
""" | |
#Decorator approach | |
def singleton(class_): | |
instances = {} | |
def getinstance(*args, **kwargs): | |
if class_ not in instances: | |
instances[class_] = class_(*args,**kwargs) | |
return instances[class_] | |
return getinstance | |
@singleton | |
class TestClass(): | |
def __init__(self, value): | |
self.value = value | |
def getValue(self): | |
return self.value | |
#Approach 2: | |
#Metaclass | |
class Singleton( type ): | |
_instances = {} | |
def __call__(cls, *args, **kwargs): | |
if cls not in cls._instances: | |
cls._instances[cls] = super( Singleton, cls ).__call__(*args,**kwargs) | |
return cls._instances[cls] | |
class MyClass(): | |
__metaclass__ = Singleton | |
def __init__(self, value): | |
self.value = value | |
def getValue(self): | |
return self.value | |
if __name__ == "__main__": | |
""" Approach 1 | |
test1 = TestClass(200) | |
test2 = TestClass(400) | |
print(str(test1.getValue())) | |
print(str(test2.getValue())) | |
""" | |
""" Approach 2""" | |
class1 = MyClass( "value1" ) | |
class2 = MyClass( "value2" ) | |
print(str(class2.getValue())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment