zoukankan      html  css  js  c++  java
  • 单例模式总结

    单例模式4种方式

     

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

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

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

    1. 使用 __new__

    from django.test import TestCase
    
    # Create your tests here.
    class Singleton:
        def __init__(self,name):
            self.name=name
    
        def __new__(cls, *args, **kw):
            if not hasattr(cls, '_instance'):
                orig = super(Singleton, cls)
                cls._instance = orig.__new__(cls)
            return cls._instance
    
    one = Singleton('aa')
    two = Singleton('bb')
    print(one.name)
    print(one.name)
    
    
    
    two.a = 3
    print(one.a)
    # one和two完全相同,可以用id(), ==, is检测
    print(id(one))
    print(id(two))
    print(one == two)
    print(one is two)

    加上锁

     1 import time
     2 import threading
     3 class Singleton(object):
     4     _instance_lock = threading.Lock()
     5     def __init__(self):
     6         time.sleep(1)
     7         print(self)
     8 
     9 
    10     def __new__(cls, *args, **kwargs):
    11         with cls._instance_lock:
    12             if not hasattr(Singleton,'_instance'):
    13                 Singleton._instance=object.__new__(cls)
    14         return Singleton._instance
    15 
    16 
    17 
    18 def task():
    19     obj = Singleton()
    20 
    21 for i in range(10):
    22     t=threading.Thread(target=task)
    23     t.start()
    View Code

    2.使用模块

    可以参考自定义增删改查组件site对象,很明显的单利模式

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

    # mysingleton.py
    class My_Singleton(object):
        def foo(self):
            pass
     
    my_singleton = My_Singleton()

    将上面的代码保存在文件 mysingleton.py 中,然后这样使用:

    from mysingleton import my_singleton
     
    my_singleton.foo()

    3.利用类实现单例模式:

    实现支持多线程的单列模式:

    
    
    import time
    import threading
    class Singleton(object):
        _instance_lock = threading.Lock()
        def __init__(self):
    
            time.sleep(1)
    
        @classmethod
        def instance(cls,*args,**kwargs):
            with cls._instance_lock:
                if not hasattr(Singleton,'_instance'):
                    Singleton._instance=Singleton()
                    return Singleton._instance
                return Singleton._instance
    
    def task():
    
        obj = Singleton.instance()
        print(obj)
    
    
    for i in range(10):
        t=threading.Thread(target=task)
        t.start()
     

    问题:

    创建实例只能调用Singleton.instance()来调用,不能用Singleton()来实现

    四、基于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):
            print(1)
            super(SingletonType,self).__init__(*args,**kwargs)
    
        def __call__(cls, *args, **kwargs):
            print(2)
            obj = cls.__new__(cls,*args, **kwargs)
            cls.__init__(obj,*args, **kwargs) # Foo.__init__(obj)
            return obj
    
    class Foo(metaclass=SingletonType):
        def __init__(self,name):
            print(4)
            self.name = name
        def __new__(cls, *args, **kwargs):
            print(3)
            return object.__new__(cls)
    
    obj1 = Foo('name')

    实现单例

    import threading
    class Singleton(type):
        _instance_lock=threading.Lock()
        def __call__(cls, *args, **kwargs):
            with  cls._instance_lock:
                if not hasattr(cls,'_instance'):
                    cls._instance=super(Singleton, cls).__call__(*args, **kwargs)
            return cls._instance
    
    
    class Foo(metaclass=Singleton):
        def __init__(self,name):
            self.name=name
    
    
    obj1 = Foo('name')
    obj2 = Foo('name')
    print(obj1,obj2)
  • 相关阅读:
    P4665 [BalticOI 2015]Network 题解
    NOIp2020游记
    独立集(bubble) 题解
    密码(substring) 题解
    8.20被题虐
    开通博客了!
    CSP-S2021 记
    「CSP-S 2020」函数调用(拓扑排序+DP)
    OI生涯回忆录
    [UOJ79]一般图最大匹配(带花树)
  • 原文地址:https://www.cnblogs.com/qianniao2122/p/11923288.html
Copyright © 2011-2022 走看看