Created
December 24, 2013 17:05
-
-
Save mdeous/8115735 to your computer and use it in GitHub Desktop.
Python Implementation of the Singleton Design Pattern
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
| class Singleton(type): | |
| def __init__(cls, *args, **kwargs): | |
| # When creating the class object (class ClassName), set the shared instance variable. | |
| super(Singleton, cls).__new__(*args, **kwargs) | |
| cls.__instance = None | |
| def __call__(cls, *args, **kwargs): | |
| # When instanciating (obj = ClassName()), return shared instance (or create it if 1st time). | |
| if cls.__instance is None: | |
| cls.__instance = super(Singleton, cls).__call__(*args, **kwargs) | |
| return cls.__instance |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment