Last active
November 20, 2015 07:54
-
-
Save taozle/faf32d0d781eff0ebf7a to your computer and use it in GitHub Desktop.
Singleton implementations
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
import functools | |
def singleton(cls, *args, **kwargs): | |
instances = {} | |
@functools.wraps(cls) | |
def wrapper(): | |
if cls not in instances: | |
instances[cls] = cls(*args, **kwargs) | |
return instances[cls] | |
return wrapper |
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 Singleton(type): | |
def __init__(self, name, bases, dct): | |
super(Singleton, self).__init__(name, bases, dct) | |
self.instance = None | |
def __call__(self, *args, **kw): | |
if self.instance is None: | |
self.instance = super(Singleton, self).__call__(*args, **kw) | |
return self.instance | |
class A(object): | |
__metaclass__ = Singleton | |
def __init__(self): | |
self.xx = 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment