1、什么是单例模式?
单例模式指的是多种不同的实例化指向同一个实例
2、为何要去用单例模式?
使用单例模式是为了减少资源的浪费
3、如何去用单例模式?
方式一:
#先写一个setting模块用来存放(ip=None,port=None) import setting class Mysql: __instance=None def __init__(self,ip,port): self.ip=ip self.port=port @classmethod def srea(cls): if cls.__instance is None: cls.__instance=cls(setting.ip,setting.port) return cls.__instance obj=Mysql.srea() obj1=Mysql('1.1.1.1',203) print(obj) print(obj1)
方式二:
先写一个setting模块用来存放(ip=None,port=None)
import setting def atuh(cls): _instance=cls(setting.ip,setting.port) def warpper(*args,**kwargs): if args or kwargs: obi=cls(*args,**kwargs) return obi return _instance return warpper @atuh class Mysql: def __init__(self,ip,port): self.ip=ip self.port=port obj=Mysql() obj1=Mysql() obj2=Mysql('1.1.1.1',2206) print(obj) print(obj1) print(obj2)
方式三:
先写一个setting模块用来存放(ip=None,port=None)
import setting class Mymeta(type): def __init__(self,mysql,mysql_obj,mysql_dic): self._instance=self(setting.ip,setting.port) def __call__(self, *args, **kwargs): if args or kwargs: obj=self.__new__(self) self.__init__(obj,*args,**kwargs) return obj else: return self._instance class Mysql(metaclass=Mymeta): def __init__(self,ip,port): self.ip=ip self.port=port obj=Mysql() obj1=Mysql() obj2=Mysql('1.1.1.3',2206) print(obj) print(obj1) print(obj2)
方式四:
先写一个setting模块用来存放(ip=None,port=None)再写一个song模块
song模块的代码如下:class Mysql: def __init__(self,ip,port): self.ip=ip self.port=port instance=Mysql('1.1.1.1',2206) 主题代码吐下: def f(): from song import instance print(instance) def f2(): from song import instance, Mysql odj=Mysql('1.1.1.1',2206) print(odj) f() f2()