Last active
August 29, 2015 14:05
-
-
Save charlesreid1/7d413ac914cee4ada47a to your computer and use it in GitHub Desktop.
Python Singleton Wrapper (Design Pattern)
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
class ExpensiveObjectToCreate(object): | |
'''Insert code here''' | |
pass | |
def __init__(self,**kwargs): | |
self.params = kwargs | |
def check(self): | |
print self.params | |
class SingletonWrapper(object): | |
""" | |
Wraps an expensive-to-create object that only needs to be initialized once. | |
""" | |
def __new__(self,**kwargs): | |
""" | |
Returns the expensive object, self.bling | |
""" | |
try: | |
return self.bling | |
except AttributeError: | |
self.bling = ExpensiveObjectToCreate(**kwargs) | |
return self.bling | |
if __name__=="__main__": | |
d = { 'a':1, | |
'b':2, | |
'c':'dog'} | |
print "Init data:" | |
print d | |
print "Creating an instance of the singleton wrapper..." | |
ps = SingletonWrapper(**d) | |
print "Done.\n" | |
print "Creating a second instance of the singleton wrapper..." | |
ps2 = SingletonWrapper() | |
print "Done.\n" | |
print "Here's the second instance's data:" | |
ps2.check() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment