单例模式是一种设计模式一次只允许产生一个实例对象.
实现方法有很多,常见的方法有五种:
1.classmethod
class Mysql: _instance = None def __init__(self,host,port): self.host = host self.port = port @classmethod def singleton(cls): if not cls.singleton: _instance = cls('127.0.0.1',3306) return cls._instance print(id(Mysql.singleton())) print(id(Mysql.singleton()))
2.装饰器
from functools import wraps def singleton(cls): cls._instance = cls('127.0.0.1',3306) @wraps(cls) def inner(*args,**kwargs): if args or kwargs: obj = cls(*args,**kwargs) return obj return cls._instance return inner @singleton # Mysql = singleton(Mysql) class Mysql: def __init__(self,host,port): self.host = host self.port = port obj1 = Mysql() obj2 = Mysql() print(id(obj1),id(obj2))
3.基于元类
class MymetaClass(type): def __call__(self,*args,**kwargs): if not getattr(self,'_instance'): self._instance = super().__call__(*args,**kwargs) return self._instance class Mysql(metaclass = MymetaClass): _instance =None def __init__(self,host,port): self.host = host self.port = port print(id(Mysql('127.9.0.1',9090))) print(id(Mysql('127.9.0.2',9090)))
4基于__new__
class Singleton(object): _instance = None def __new__ (cls,*args,**kw): if not cls._instance: cls._instance = super(Singleton,cls).__new__(cls,*args,**kwargs) return cls._instance
5基于模块(最常用!)
# demo.py class Setting(): pass settings = Setting() # start.py from demo import settings # settings被导入任何模块都是同一对象
以上五种方法,模块最简单也最常用.