美文网首页
python3 什么是单例模式及单例模式的实现

python3 什么是单例模式及单例模式的实现

作者: 小梨的十三 | 来源:发表于2019-06-24 23:35 被阅读0次

    单例模式的理解

    单例模式(Singleton Pattern)是一种常用的软件设计模式,该模式的主要目的是确保某一个类只有一个实例存在。当你希望在整个系统中,某个类只能出现一个实例时,单例对象就能派上用场。

    为什么要使用单例模式?

    比如,某个程序的全局配置信息存放在一个文件中,客户端需要多次读取配置文件的信息。如果在程序运行期间,有很多地方都需要使用配置文件的内容,也就是说,很多地方都需要创建 AppConfig 对象的实例,这就导致系统中存在多个 AppConfig 的实例对象,而这样会严重浪费内存资源,尤其是在配置文件内容很多的情况下。事实上,类似 AppConfig 这样的类,我们希望在程序运行期间只存在一个实例对象。这个时候就要用到我们的单例模式

    在 Python 中,我们可以用多种方法来实现单例模式:

    方法一:使用模块。

    Python 的模块就是天然的单例模式,因为模块在第一次导入时,会生成 .pyc 文件,当第二次导入时,就会直接加载 .pyc 文件,而不会再次执行模块代码。因此,我们只需把相关的函数和数据定义在一个模块中,就可以获得一个单例对象了。如果我们真的想要一个单例类,可以考虑这样做:

    pakeage.py
    
    class Save(object):
        def save(self):
            print("save")
    save = Save()
    
    # 将上面的代码保存在文件 pakeage.py 中,要使用时,直接在其他文件中导入此文件中的对象,这个对象即是单例模式的对象
    from a import save
    

    方法二:基于 _ new _ 方法实现(推荐使用,方便)

    当我们实例化一个对象时,是先执行了类的new方法(我们没写时,默认调用object.new),实例化对象;然后再执行类的init方法,对这个对象进行初始化,所有我们可以基于这个,实现单例模式

    import threading
    
    
    class Singleton:
        _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 = super(Singleton, cls).__new__(cls, *args, **kwargs)
            return Singleton._instance
    
    
    obj1 = Singleton()
    obj2 = Singleton()
    print(obj1, obj2)
    
    
    def task(arg):
        obj = Singleton()
        print(obj,arg)
    
    
    for i in range(10):
        t = threading.Thread(target=task, args=(i,))
        t.start()
    
    
    输出结果:
    <__main__.Singleton object at 0x1097a8cf8> <__main__.Singleton object at 0x1097a8cf8>
    <__main__.Singleton object at 0x1097a8cf8> 0
    <__main__.Singleton object at 0x1097a8cf8> 1
    <__main__.Singleton object at 0x1097a8cf8> 2
    <__main__.Singleton object at 0x1097a8cf8> 3
    <__main__.Singleton object at 0x1097a8cf8> 4
    <__main__.Singleton object at 0x1097a8cf8> 5
    <__main__.Singleton object at 0x1097a8cf8> 6
    <__main__.Singleton object at 0x1097a8cf8> 7
    <__main__.Singleton object at 0x1097a8cf8> 8
    <__main__.Singleton object at 0x1097a8cf8> 9
    

    方法三:使用类

    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,arg)
    for i in range(10):
        t = threading.Thread(target=task,args=(i,))
        t.start()
    time.sleep(20)
    obj = Singleton.instance()
    print(obj)
    

    这种方式实现的单例模式,使用时会有限制,以后实例化必须通过 obj = Singleton.instance()

    with Lock相当于自动获取锁和释放锁(资源)

    方法四:使用装饰器

    def Singleton(cls):
        _instance = {}
    
        def _singleton(*args, **kargs):
            print(cls,_instance)
            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(a1,a2)
    
    输出结果:
    <__main__.A object at 0x1043df2e8> <__main__.A object at 0x1043df2e8>
    

    方法五:基于metaclass方式实现

    1.类由type创建,创建类时,type的init方法自动执行,类() 执行type的 call方法(类的new方法,类的init方法)
    2.对象由类创建,创建对象时,类的init方法自动执行,对象()执行类的 call 方法

    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)
    

    相关文章

      网友评论

          本文标题:python3 什么是单例模式及单例模式的实现

          本文链接:https://www.haomeiwen.com/subject/wxxzqctx.html