2019.9.4学习整理
单例模式
什么是单例模式
单例模式:基于某种某种方法实例化多次得到实例是同一个
为什么用单例模式
当实例化多次得到的对象中存放的属性都一样的情况,应该将多个对象指向同一个内存,即同一个实例
单例模式的四种方法
1.单例模式(类的绑定方法)
#settings.py
PORT=3306
HOST='127.0.0.1'
class Mysql:
_instacane=None
def __init__(self,PORT,HOST):
self.PORT=PORT
self.HOST=HOST
@classmethod
def get_sigoleton(cls):
import settings
if cls._instacane:
return cls._instacane
else:
cls._instacane=cls(settings.PORT,settings.HOST)
return cls._instacane
s1=Mysql.get_sigoleton()
s2=Mysql.get_sigoleton()
s3=Mysql(3306,'172.0.0.1')
print(s1)
print(s2)
print(s3)
2.通过装饰器
#settings.py
PORT=3306
HOST='127.0.0.1'
def get_sigoleton(cls):
import settings
_instance=cls(settings.PORT,settings.HOST)
def wrapper(*args,**kwargs):
if len(args)!=0 or len(kwargs)!=0:
res=cls(*args,**kwargs)
return res
else:
return _instance
return wrapper
@get_sigoleton
class Mysql():
def __init__(self,PORT,HOST):
self.PORT=PORT
self.HOST=HOST
s1=Mysql()
s2=Mysql()
s3=Mysql('3306','192.168.1.1')
s4=Mysql('3306','192.168.1.1')
print(s1)
print(s2)
print(s3)
print(s4)
3.通过元类
#settings.py
PORT=3306
HOST='127.0.0.1'
class Mymate(type):
def __init__(self,name,bases,dic):
import settings
self._instance=self(settings.PORT,settings.HOST)
def __call__(self, *args, **kwargs):
if len(args)!=0 or len(kwargs)!=0:
obj=object.__new__(self)
obj.__init__(*args,**kwargs)
return obj
else:
return self._instance
class Mysql(metaclass=Mymate):
def __init__(self,PORT,HOST):
self.PORT=PORT
self.HOST=HOST
s1=Mysql()
s2=Mysql()
s3=Mysql(3306,'127.0.1.1')
print(s1)
print(s2)
print(s3)
4.使用模块
#settings.py
PORT=3306
HOST='127.0.0.1'
#sigoleton.py
import settings
class Mysql():
def __init__(self, PORT, HOST):
self.PORT = PORT
self.HOST = HOST
s1 = Mysql(settings.PORT, settings.HOST)
def test():
from sigoleton import s1
print(s1)
def test1():
from sigoleton import s1 as s2
print(s2)
test()
test1()
from sigoleton import s1
from sigoleton import Mysql
s2=Mysql(3306,'192.168.1.1')
print(s1)
print(s2)