Skip to content

Instantly share code, notes, and snippets.

@mfalade
Last active February 23, 2017 15:29
Show Gist options
  • Save mfalade/cf50c593988d4df600379d0e9187cc2b to your computer and use it in GitHub Desktop.
Save mfalade/cf50c593988d4df600379d0e9187cc2b to your computer and use it in GitHub Desktop.
A simple illustration of the Singleton pattern in Python
class Singleton:
the_actual_instance = None
class _Singleton:
"""
The actual implementation of the Singleton class should reside here
"""
def __init__(self):
self.name = 'mayor'
print('this should only be printed once.. i.e this class should only be instantiated once.')
def create_room(self, room_name):
print 'I see you are trying to create a new room ', room_name
def __init__(self):
if not Singleton.the_actual_instance:
print('Fresh start')
Singleton.the_actual_instance = Singleton._Singleton()
print Singleton.the_actual_instance, '.....'
else:
pass
def __getattr__(self, required_attribute):
return getattr(self.the_actual_instance, required_attribute)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment