python singleton

coding:utf-8

class _SingletonWrapper:
"""
A singleton wrapper class. Its instances would be created
for each decorated class.
"""

def init(self, cls):
self.wrapped = cls
self._instance = None

def call(self, args, **kwargs):
"""Returns a single instance of decorated class"""
if self._instance is None:
self._instance = self.wrapped(
args, **kwargs)
return self._instance

def singleton(cls):
"""
A singleton decorator. Returns a wrapper objects. A call on that object
returns a single instance object of decorated class. Use the wrapped
attribute to access decorated class directly in unit tests
"""
return _SingletonWrapper(cls)

@singleton
class Singleton:
def init(self):
self.state = 'a'

p1 = Singleton()
p2 = Singleton()
p3 = Singleton()

print p1==p3

posted @ 2017-02-04 14:18  idlewith  阅读(150)  评论(0)    收藏  举报