#单例模式 : 多次实例化结果指向同一个实例
第一种 (基于classmethod)
class Mysql(object):
_instance = None
def __init__(self,ip,port):
self.ip = ip
self.port = port
@classmethod
def singleton(cls):
if not cls._instance:
cls._instance = Mysql('127.0.0.1',3306)
return cls._instance
obj1 = Mysql.singleton()
obj2 = Mysql.singleton()
print(obj1) #<__main__.Mysql object at 0x0000016C9659D048>
print(obj2) #<__main__.Mysql object at 0x0000016C9659D048>
第二种(基于装饰器)
def singleton(cls):
#该对象在类Mysql被装饰上singleton的时候就已经实例化完毕
_instance = cls('127.0.0.1',3306)
def inner(*args,**kwargs):
#判断是否传入参数,传入参数表示要实例化新的,不传表示默认的
if args or kwargs:
obj = cls(*args,**kwargs)
return obj
return _instance
return inner
@singleton
class Mysql:
def __init__(self,ip,port):
self.ip = ip
self.port = port
obj1 = Mysql(666,123) #<__main__.Mysql object at 0x0000011AA9F64630>
obj2 = Mysql() #<__main__.Mysql object at 0x0000011AA9F54F28>
obj3 = Mysql() #<__main__.Mysql object at 0x0000011AA9F54F28>
print(obj1,obj2,obj3)
第三种(基于元类)
class MymeteClass(type):
def __call__(self, *args, **kwargs):
if not hasattr(self,'instance'):
self.instance = super().__call__(*args,**kwargs)
return self.instance
class Mysql(metaclass=MymeteClass):
def __init__(self,host,port):
self.host = host
self.port = port
obj = Mysql('asdf',123)
obj1 = Mysql()
print(obj,obj1) #<__main__.Mysql object at 0x0000016161CEE320> <__main__.Mysql object at 0x0000016161CEE320>
第四种(基于__new__)
class Singleton(object):
_instance =None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(Singleton,cls).__new__(cls,*args,**kwargs)
return cls._instance
class MyClass(Singleton):
a = 1
obj1 = MyClass()
obj2 = MyClass()
print(obj1,obj2) #<__main__.MyClass object at 0x000001AF7FB9C518> <__main__.MyClass object at 0x000001AF7FB9C518>
第五种(基于模块)
#单独在一个py文件中定义一个类,并实例化一个对象,之后在其他文件导入这一个对象,实现单例
class Singleton(object):
def __int__(self,host,port):
self.host = host
self.port = port
singleton = Singleton('127.0.0.1',3306)