python 设计模式-单例模式

单例模式使用场景详解

单例模式的优势与劣势这里就不做讲解,主要总结了下python的经常使用场景

python类封装-单例模式

#  单一类封装,只能创建一个实例
class Singleton(object):
    _instance = None
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            # 初始化父类python2和python3通用
            cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
        return cls._instance

    def __init__(self, name=None):
        if name:
            self.name = name
# 适用于设计抽象类,基类保证子类只能创建一个实例
class Singleton(object):
    # 如果该类已经有了一个实例则直接返回,否则创建一个全局唯一的实例
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
        return cls._instance

class MyClass(Singleton):
    def __init__(self, name=None):
        if name:
            self.name = name
from functools import wraps
# 类装饰器,此种方式构造单例模式比较方便
def singleton(cls):
    instances = {}

    @wraps(cls)
    def _singleton(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]

    return _singleton


@singleton
class MysqlOpers:
    def __init__(self):
        print('建立mysql连接')
        # 伪代码  self.db = MySQLdb.connect() 

    def select(self):
        pass

# 三个print打印的对象id相同,说明只创建了一个类对象
print(id(MysqlOpers()))
print(id(MysqlOpers()))
print(id(MysqlOpers()))

 数据库连接池是对单例模式应用的一个典例,按约定创建一定数量的连接对象,对对象的创建和释放都合理控制,防止资源滥用,适用于高并发从数据库中查询数据的接口设计

import pymysql
from DBUtils.PooledDB import PooledDB, SharedDBConnection
 
POOL = PooledDB(
    creator=pymysql,  # 使用链接数据库的模块
    maxconnections=20,  # 连接池允许的最大连接数,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=4,
    # 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='123',
    database='pooldb',
    charset='utf8'
)
 
 
class SqlHelper(object):
 
    def open(self, ):
        self.conn = POOL.connection()
        self.cursor = self.conn.cursor()
 
    def close(self, ):
        self.cursor.close()
        self.conn.close()
 
    def __enter__(self, ):
        self.open()
        return self
 
    def fetchone(self, sql):
        self.cursor.execute(sql)
        result = self.cursor.fetchall()
        return result
 
    def fetchall(self, sql):
        self.cursor.execute(sql)
        result = self.cursor.fetchall()
        return result
 
    def __exit__(self, ):
        self.close()
 
 
with SqlHelper as db:
    db.fetchall("select * from tp_sys_user")

此处一定要注意,单例模式是多线程不安全的,如果多个线程同时访问单例模式方法,在访问的那一刻,发现没有创建实例,然后每个线程都创建就会引发不可预知的后果,所以多线程在使用单例模式时,一定要加锁;

如下是实现了一个对单例模式加锁的装饰器,使用时直接在单例模式方法开头调用就好

import threading
from functools import wraps

def synchronized(func):
    func.__lock__ = threading.Lock()
    @wraps(func)
    def synced_func(*args, **kws):
        with func.__lock__:
            return func(*args, **kws)

    return synced_func

猜你喜欢

转载自blog.csdn.net/u012089823/article/details/88136738
今日推荐