1.import方法【调用此文件一次,也算是单例模式的一种】
# mysingleton.py------------------------------
"""
class MySingleton(object):
def foo(self):
pass
singleton = MySingleton( )
"""
# test.py-----------------------------------------
"""
from mysingleton import singleton
singleton.foo()
"""
2.使用@classmethod内置装饰器
注意:MyClass被实例化一次(适用于连接数据库)
注意:遇到多线程,同时创建这个类的实例的时候就会出现问题
class Singleton(object):
def __init__(self,*args,**kwargs):
print('这是A的类的初始化方法')
@classmethod
def get_instance(cls, *args, **kwargs):
if not hasattr(Singleton, '_instance'):
Singleton._instance = Singleton(*args, **kwargs)
return Singleton._instance
for i in range(10):
s1 = Singleton.get_instance()
print(type(s1))
print(id(s1))
输出:
这是A的类的初始化方法
<class '__main__.Singleton'>
1742170068872
<class '__main__.Singleton'>
1742170068872
<class '__main__.Singleton'>
1742170068872
<class '__main__.Singleton'>
1742170068872
<class '__main__.Singleton'>
1742170068872
<class '__main__.Singleton'>
1742170068872
<class '__main__.Singleton'>
1742170068872
<class '__main__.Singleton'>
1742170068872
<class '__main__.Singleton'>
1742170068872
<class '__main__.Singleton'>
1742170068872
3.使用自定义装饰器:
注意:MyClass被实例化一次(可以保存多个单例模式的对象)
# coding=utf-8
def singleton(cls):
_instances = {}
def getinstance(*args, **kw):
if cls not in _instances:
_instances[cls] = cls(*args, **kw)
return _instances[cls]
return getinstance
@singleton
class MyClass(object):
def __init__(self):
print('这是A的类的初始化方法')
for i in range(10):
a1 = MyClass()
print(type(a1))
print(id(a1))
输出:
这是A的类的初始化方法
<class '__main__.MyClass'>
1966882396616
<class '__main__.MyClass'>
1966882396616
<class '__main__.MyClass'>
1966882396616
<class '__main__.MyClass'>
1966882396616
<class '__main__.MyClass'>
1966882396616
<class '__main__.MyClass'>
1966882396616
<class '__main__.MyClass'>
1966882396616
<class '__main__.MyClass'>
1966882396616
<class '__main__.MyClass'>
1966882396616
<class '__main__.MyClass'>
1966882396616
4.使用__new__方法
注意:每调用MyClass被实例化一次
class Singleton(object):
def __init__(self,*args,**kwargs):
print('这是A的类的初始化方法')
def __new__(cls, *args, **kwargs):
if not hasattr(cls, "_instance"):
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
return cls._instance
class Foo(Singleton):
pass
if __name__ == '__main__':
foo1 = Foo( )
for i in range(10):
foo = Foo( )
assert foo1 == foo
assert foo1 is foo
输出:
这是A的类的初始化方法
这是A的类的初始化方法
这是A的类的初始化方法
这是A的类的初始化方法
这是A的类的初始化方法
这是A的类的初始化方法
这是A的类的初始化方法
这是A的类的初始化方法
这是A的类的初始化方法
这是A的类的初始化方法
这是A的类的初始化方法
5.共享属性
注意:没有执行初始化方法
class Singleton(object):
_state = {"aa": "11", "bb": "22"}
def __init__(self, *args, **kwargs):
print('这是A的类的初始化方法')
def __new__(cls, *args, **kwargs):
ob = super(Singleton, cls).__new__(cls, *args, **kwargs)
ob.__dict__ = cls._state
return ob.__dict__
class Foo(Singleton):
pass
if __name__ == '__main__':
foo1 = Foo( )
for i in range(10):
foo = Foo( )
print(foo)
assert foo1 == foo
assert foo1 is foo
输出:
{'aa': '11', 'bb': '22'}
{'aa': '11', 'bb': '22'}
{'aa': '11', 'bb': '22'}
{'aa': '11', 'bb': '22'}
{'aa': '11', 'bb': '22'}
{'aa': '11', 'bb': '22'}
{'aa': '11', 'bb': '22'}
{'aa': '11', 'bb': '22'}
{'aa': '11', 'bb': '22'}
{'aa': '11', 'bb': '22'}
6.扩展1
# coding=utf-8
class Singleton(type):
"""
定义一个实例操作,使客户端可以访问其唯一实例。
"""
def __init__(cls, name, bases, attrs, **kwargs):
super( ).__init__(name, bases, attrs)
cls._instance = None
def __call__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super( ).__call__(*args, **kwargs)
return cls._instance
class MyClass(metaclass = Singleton):
pass
def main( ):
m1 = MyClass( )
m2 = MyClass( )
m3 = MyClass( )
assert m1 is m2
assert m1 is m3
assert m2 is m3
if __name__ == "__main__":
main( )
6.扩展1
class Singleton(type):
def __call__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instance
# Python2
# class Foo(object):
# __metaclass__ = Singleton
# Python3
class Foo(metaclass = Singleton):
pass
if __name__ == '__main__':
foo1 = Foo( )
for i in range(10):
foo = Foo( )
assert foo1 == foo
assert foo1 is foo