Flask中的单例模式
1,基于⽂件的单例模式:
import pymysql
import threading
from DBUtils.PooledDB import PooledDB
class SingletonDBPool(object):
_instance_lock = threading.Lock()
def __init__(self):
self.pool = PooledDB(
creator=pymysql,  # 使⽤链接数据库的模块
maxconnections=6,  # 连接池允许的最⼤连接数,0和None表⽰不限制连接数
mincached=2,  # 初始化时,链接池中⾄少创建的空闲的链接,0表⽰不创建
maxcached=5,  # 链接池中最多闲置的链接,0和None不限制
maxshared=3,
# 链接池中最多共享的链接数量,0和None表⽰全部共享。PS: ⽆⽤,因为pymysql和MySQLdb等模块的 threadsafety都为1,所有值⽆论设置为多少,_maxcached永远为0,所以永远是所有链接都共享。            blocking=True,  # 连接池中如果没有可⽤连接后,是否阻塞等待。True,等待;False,不等待然后报错
maxusage=None,  # ⼀个链接最多被重复使⽤的次数,None表⽰⽆限制
setsession=[],  # 开始会话前执⾏的命令列表。如:["set datestyle to ...", "set time zone ..."]
ping=0,
# ping MySQL服务端,检查是否服务可⽤。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always
host='127.0.0.1',
port=3306,
user='root',
password='123456',
database='pooldb',
charset='utf8'
)
def __new__(cls, *args, **kwargs):
if not hasattr(SingletonDBPool, "_instance"):
with SingletonDBPool._instance_lock:
if not hasattr(SingletonDBPool, "_instance"):
SingletonDBPool._instance = object.__new__(cls, *args, **kwargs)
return SingletonDBPool._instance
def connect(self):
return tion()
from pool import SingletonDBPool
def run():
pool = SingletonDBPool()
con = t()
# xxxxxx
con.close()
if __name__ == '__main__':
run()
# 单例模式:⽆法⽀持多线程情况
"""
class Singleton(object):
def __init__(self):
import time
time.sleep(1)
@classmethod
def instance(cls, *args, **kwargs):
if not hasattr(Singleton, "_instance"):
Singleton._instance = Singleton(*args, **kwargs)
return Singleton._instance
import threading
def task(arg):
obj = Singleton.instance()
print(obj)
for i in range(10):
t = threading.Thread(target=task,args=[i,])
t.start()
"""
# # 单例模式:⽀持多线程情况
"""
import time
import threading
class Singleton(object):
_instance_lock = threading.Lock()
def __init__(self):
time.sleep(1)
@classmethod
def instance(cls, *args, **kwargs):
if not hasattr(Singleton, "_instance"):
with Singleton._instance_lock:
if not hasattr(Singleton, "_instance"):
Singleton._instance = Singleton(*args, **kwargs)
return Singleton._instance
def task(arg):
obj = Singleton.instance()
print(obj)
for i in range(10):
t = threading.Thread(target=task,args=[i,])
t.start()
time.sleep(20)
obj = Singleton.instance()
print(obj)
"""
基于__new__⽅法实现单例模式
# class Singleton(object):
#    def __init__(self):
#        print('init',self)
#
#
#    def __new__(cls, *args, **kwargs):
#        o = object.__new__(cls, *args, **kwargs)
#        print('new',o)
#        return o
#
# obj = Singleton()
#
# print('xxx',obj)
import time
import threading
java单例模式双重锁class Singleton(object):
_instance_lock = threading.Lock()
def __init__(self):
pass
def __new__(cls, *args, **kwargs):
if not hasattr(Singleton, "_instance"):
with Singleton._instance_lock:
if not hasattr(Singleton, "_instance"):
Singleton._instance = object.__new__(cls, *args, **kwargs)
return Singleton._instance
obj1 = Singleton()
obj2 = Singleton()
print(obj1,obj2)
# def task(arg):
#    obj = Singleton()
#    print(obj)
#
# for i in range(10):
#    t = threading.Thread(target=task,args=[i,])
#    t.start()
基于metaclass
"""
1.对象是类创建,创建对象时候类的__init__⽅法⾃动执⾏,对象()执⾏类的 __call__ ⽅法
2.类是type创建,创建类时候type的__init__⽅法⾃动执⾏,类() 执⾏type的 __call__⽅法(类的__new__⽅法,类的__init__⽅法) # 第0步: 执⾏type的 __init__ ⽅法【类是type的对象】
class Foo:
def __init__(self):
pass
def __call__(self, *args, **kwargs):
pass
# 第1步: 执⾏type的 __call__ ⽅法
#        1.1  调⽤ Foo类(是type的对象)的 __new__⽅法,⽤于创建对象。
#        1.2  调⽤ Foo类(是type的对象)的 __init__⽅法,⽤于对对象初始化。
obj = Foo()
# 第2步:执⾏Foodef __call__ ⽅法
obj()
"""
"""
class SingletonType(type):
def __init__(self,*args,**kwargs):
super(SingletonType,self).__init__(*args,**kwargs)
def __call__(cls, *args, **kwargs):
obj = cls.__new__(cls,*args, **kwargs)
cls.__init__(obj,*args, **kwargs) # Foo.__init__(obj)
return obj
class Foo(metaclass=SingletonType):
def __init__(self,name):
self.name = name
def __new__(cls, *args, **kwargs):
return object.__new__(cls, *args, **kwargs)
obj = Foo('name')
"""
import threading
class SingletonType(type):
_instance_lock = threading.Lock()
def __call__(cls, *args, **kwargs):
if not hasattr(cls, "_instance"):
with SingletonType._instance_lock:
if not hasattr(cls, "_instance"):
cls._instance = super(SingletonType,cls).__call__(*args, **kwargs)
return cls._instance
class Foo(metaclass=SingletonType):
def __init__(self,name):
self.name = name
obj1 = Foo('name')
obj2 = Foo('name')
print(obj1,obj2)
# >>>>#### 基于类⽅法实现 >>>>> """
import time
import threading
class Singleton(object):
_instance_lock = threading.Lock()
def __init__(self):
time.sleep(1)
@classmethod
def instance(cls, *args, **kwargs):
if not hasattr(Singleton, "_instance"):
with Singleton._instance_lock:
if not hasattr(Singleton, "_instance"):
Singleton._instance = Singleton(*args, **kwargs)
return Singleton._instance
# 使⽤先说明,以后⽤单例模式,obj = Singleton.instance()
# ⽰例:
# obj1 = Singleton.instance()
# obj2 = Singleton.instance()
# print(obj1,obj2)
# 错误⽰例
# obj1 = Singleton()
# obj2 = Singleton()
# print(obj1,obj2)
"""
# >>>>> 基于__new__⽅式实现 >>>>> """
import time
import threading
class Singleton(object):
_instance_lock = threading.Lock()
def __init__(self):
pass
def __new__(cls, *args, **kwargs):
if not hasattr(Singleton, "_instance"):
with Singleton._instance_lock:
if not hasattr(Singleton, "_instance"):
Singleton._instance = object.__new__(cls, *args, **kwargs)
return Singleton._instance
# 使⽤先说明,以后⽤单例模式,obj = Singleton()
# ⽰例
# obj1 = Singleton()
# obj2 = Singleton()
# print(obj1,obj2)
"""
# >>>>> 基于metaclass⽅式实现 >>>#### """
import threading
class SingletonType(type):
_instance_lock = threading.Lock()
def __call__(cls, *args, **kwargs):
if not hasattr(cls, "_instance"):
with SingletonType._instance_lock:
if not hasattr(cls, "_instance"):
cls._instance = super(SingletonType,cls).__call__(*args, **kwargs)
return cls._instance
class Foo(metaclass=SingletonType):
def __init__(self,name):
self.name = name
obj1 = Foo('name')
obj2 = Foo('name')
print(obj1,obj2)
"""
# PS: 为了保证线程安全在内部加⼊锁
# 装饰器实现的单例模式
#
def wrapper(cls):
instance = {}
def inner(*args,**kwargs):
if cls not in  instance:
instance[cls] = cls(*args,**kwargs) return instance[cls]
return inner
@wrapper
class Singleton(object):
def__init__(self,name,age):
self.name = name
self.age = age
obj1 = Singleton('haiyan',22)
obj2 = Singleton('xx',22)
print(obj1)
print(obj2)

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。

发表评论