初步实现代码如下:
class Singleton(object): instance = None def __init__(self): pass @staticmethod def get_instance(): if Singleton.instance is None: Singleton.instance = Singleton() return Singleton.instance a = Singleton.get_instance() b = Singleton.get_instance() c = Singleton() print('a id=', id(a)) print('b id=', id(b))
输出:
>>> a id= 39119224 >>> b id= 39119224
class Singleton(object): instance = None def __init__(self): pass @staticmethod def get_instance(): if Singleton.instance is None: Singleton.instance = Singleton() return Singleton.instance a = Singleton.get_instance() b = Singleton.get_instance() c = Singleton() print('a id=', id(a)) print('b id=', id(b)) print('c id=', id(c))
输出:
>>> a id= 39119056 >>> b id= 39119056 >>> c id= 39117992c是通过类实例化的id和a、b的不一样。
有没有办法禁止通过类来实例化呢?我们可以在__init__中做文章,在__init__中抛出异常即可禁止实例化了,但是还是有问题,因为get_instance里面就是通过类来实例化的:
@staticmethod def get_instance(): if Singleton.instance is None: Singleton.instance = Singleton() return Singleton.instance
@staticmethod def get_instance(): if Singleton.instance is None: Singleton.instance = object.__new__(Singleton) return Singleton.instance
完整代码如下:
class Singleton(object): instance = None def __init__(self): raise SyntaxError('can not instance, please use get_instance') @staticmethod def get_instance(): if Singleton.instance is None: Singleton.instance = object.__new__(Singleton) return Singleton.instance a = Singleton.get_instance() b = Singleton.get_instance() print('a id=', id(a)) print('b id=', id(b)) c = Singleton() print(id(c))
输出:
>>> Traceback (most recent call last): File "E:/Code/python3/otherTest/singleTest.py", line 18, in <module> c = Singleton() File "E:/Code/python3/otherTest/singleTest.py", line 5, in __init__ raise SyntaxError('can not instance, please use get_instance') SyntaxError: can not instance, please use get_instance >>> a id= 39184592 >>> b id= 39184592
可以看出不能通过类实例化,只能通过get_instance函数获取实例。
PS:同样的通过classmethod也能实现单例模式,见python一种用classmethod实现单例模式方法的探讨。