单例模式的几种方法,以及应用

一、类方法

1.此方法不支持多线程

import time
import threading
class Singleton():
    def __init__(self):
        time.sleep(1)

    @classmethod
    def instance(cls,*args,**kwargs):
        if not hasattr(Singleton,"_instance"):
            Singleton._instance = Singleton(*args,**kwargs)
        return Singleton._instance
# obj = Singleton.instance()
# obj2 = Singleton.instance()
def task(arg):
    obj = Singleton.instance()
    print(obj)
if __name__ == '__main__':
    for i in range(10):
        t = threading.Thread(target=task,args=(i,))
        t.start()

2.加锁,支持多线程

import time
import threading
class Singleton():
    _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()
# obj2 = Singleton.instance()
def task(arg):
    obj = Singleton.instance()
    print(obj)
if __name__ == '__main__':
    for i in range(10):
        t = threading.Thread(target=task,args=(i,))
        t.start()
time.sleep(10)
obj = Singleton.instance()
print(obj)

二、__new__方法

import time
import threading


class Singleton():
    _instance_lock = threading.Lock()

    def __init__(self):
        time.sleep(1)
        print('init', self)

    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


def task(arg):
    obj = Singleton()
    print(obj)


if __name__ == '__main__':
    for i in range(10):
        t = threading.Thread(target=task, args=(i,))
        t.start()
三、基于@metaclass创建单例模式
1.type与类间的关系
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()

2.执行顺序

class SinletonType(type):
    def __init__(self,*args,**kwargs):
        print('type.init',self)
        super(SinletonType,self).__init__(*args,**kwargs)
    def __call__(self, *args, **kwargs):
        print('type.call',self)
        obj = self.__new__(self,*args,**kwargs)
        self.__init__(obj,*args,**kwargs)
        return obj
class Foo(metaclass=SinletonType):
    def __init__(self):
        print('Foo.init')
    def __new__(cls, *args, **kwargs):
        print('Foo.new')
        return object.__new__(cls,*args,**kwargs)
obj = Foo()
'''
type.init <class '__main__.Foo'>
type.call <class '__main__.Foo'>
Foo.new
Foo.init
'''

3.单例

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 threading


def Singleton(cls):
    _instance = {}
    def _singleton(*args, **kargs):
        if cls not in _instance:
            with threading.Lock():
                if cls not in _instance:
                    _instance[cls] = cls(*args, **kargs)
        return _instance[cls]

    return _singleton


@Singleton
class A(object):
    a = 1

    def __init__(self, x=0):
        self.x = x


a1 = A(2)
a2 = A(3)
print(
    id(a1))
print(
    id(a2))
print(
    a1.x)
print(
    a2.x)

五、应用

数据库连接池+单例模式

############pool.py#######################
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='123', 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 self.pool.connection()
#app.py
from
pool import SingletonDBPool def run(): pool = SingletonDBPool() con = pool.connect() # xxxxxx con.close() if __name__ == '__main__': run()
原文地址:https://www.cnblogs.com/ldq1996/p/8244860.html