Skip to content

Instantly share code, notes, and snippets.

@sujayy1983
Created January 21, 2015 22:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sujayy1983/a35b698fccc24143774f to your computer and use it in GitHub Desktop.
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.
"""
@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