为什么要使用单例?
类中有很多很好用的方法 程序很多地方都需要使用(通过对象调用)
如果产生的地方特别多 那么会浪费一定的内存空间,所以需要使用单例
class MyMeTaClass(type):
instance = None
def __call__(self, *args, **kwargs):
if self.instance:
return self.instance
obj = super().__call__(*args, **kwargs)
self.instance = obj
return obj
class Single(metaclass=MyMeTaClass):
def __init__(self, name):
self.name = name
obj1 = Single('jason')
obj2 = Single('kevin')
obj3 = Single('tony')z
print(id(obj1), id(obj2), id(obj3))
print(obj1.name)
print(obj2.name)
print(obj3.name)
import settings
class Mysql:
__instance=None
def __init__(self,host,port):
self.host=host
self.port=port
@classmethod
def singleton(cls):
if not cls.__instance:
cls.__instance=cls(settings.HOST,settings.PORT)
return cls.__instance
obj1=Mysql('1.1.1.2',3306)
obj2=Mysql('1.1.1.3',3307)
print(obj1 is obj2)
obj3=Mysql.singleton()
obj4=Mysql.singleton()
print(obj3 is obj4)
import settings
def singleton(cls):
_instance=cls(settings.HOST,settings.PORT)
def wrapper(*args,**kwargs):
if args or kwargs:
obj=cls(*args,**kwargs)
return obj
return _instance
return wrapper
@singleton
class Mysql:
def __init__(self,host,port):
self.host=host
self.port=port
obj1=Mysql()
obj2=Mysql()
obj3=Mysql()
print(obj1 is obj2 is obj3)
obj4=Mysql('1.1.1.3',3307)
obj5=Mysql('1.1.1.4',3308)
print(obj3 is obj4)