• 类的单实例模式


    类的单实例模式

    单例模式的实现方式有:

    1.使用模块
    2.使用装饰器
    3.使用类
    4.基于__new__方法
    5.基于metaclass实现

    什么是单例模式?

    单例模式(singleton pattern)是一种常用的软件交互模式,该模式的主要目的是为了确保某个类只有一个实例存在,当你希望系统中,某个类只能出现一个实例时,单实例就可以派上用场。
    比如,某个服务器程序的配置信息存放在一个文件中,客户端通过一个 AppConfig 的类来读取配置文件的信息。如果在程序运行期间,有很多地方都需要使用配置文件的内容,也就是说,很多地方都需要创建 AppConfig 对象的实例,这就导致系统中存在多个 AppConfig 的实例对象,而这样会严重浪费内存资源,尤其是在配置文件内容很多的情况下。事实上,类似 AppConfig 这样的类,我们希望在程序运行期间只存在一个实例对象。
    在 Python 中,我们可以用多种方法来实现单例模式。

    单实例的实现方式:

    1.使用模块

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

    1 class Singleton:
    2     def foo(self):
    3         pass
    4 
    5 singleton = Singleton()
    6 
    7 #我们将上面的代码保存在一个文件中,然后去另一个文件中导入对象,此时这个对象就是一个单实例对象。
    8 from a import Singleton
    View Code

    2.使用装饰器

     1 def Singleton(cls):
     2     _instance = {}
     3 
     4     def _singleton(*args, **kwargs):
     5         if cls not in _instance:
     6             _instance[cls] = cls(*args, **kwargs)
     7         return _instance
     8     return _singleton
     9 
    10 @Singleton
    11 class A:
    12     a = 1
    13 
    14     def __init__(self, x=0):
    15         self.x = x
    16 
    17 a1 = A(2)
    18 a2 = A(3)
    19 
    20 print(id(a1),type(a1),a1)
    21 print(id(a2),type(a2),a2)
    22 >>
    23 31222880 <class 'dict'> {<class '__main__.A'>: <__main__.A object at 0x00000000022D9940>}
    24 31222880 <class 'dict'> {<class '__main__.A'>: <__main__.A object at 0x00000000022D9940>}
    View Code

    3.使用类

    class Singleton:
        def __int__(self):
            pass
    
        @classmethod
        def instance(cls, *args, **kwargs):
            if not hasattr(Singleton, '_instance'):
                Singleton._instance = Singleton(*args, **kwargs)
            return Singleton
    
    s1 = Singleton()
    s2 = Singleton()
    
    print(id(s1),type(s1),s1)
    print(id(s2),type(s2),s2)
    >>
    57504624 <class '__main__.Singleton'> <__main__.Singleton object at 0x036D7370>
    86901072 <class '__main__.Singleton'> <__main__.Singleton object at 0x052E0150>
    #一般情况下,大家以为这样就完成了单例模式,但是使用多线程的时候回出现问题
    View Code
    class Singleton:
        def __int__(self):
            pass
        @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()
    >>
    <__main__.Singleton object at 0x059AB0F0>
    <__main__.Singleton object at 0x059AB0F0>
    <__main__.Singleton object at 0x059AB0F0>
    <__main__.Singleton object at 0x059AB0F0>
    <__main__.Singleton object at 0x059AB0F0>
    <__main__.Singleton object at 0x059AB0F0>
    <__main__.Singleton object at 0x059AB0F0>
    <__main__.Singleton object at 0x059AB0F0>
    <__main__.Singleton object at 0x059AB0F0>
    <__main__.Singleton object at 0x059AB0F0>
    
    #看似是没有问题,那是因为线程的执行速度比较快,如果在init方法中添加一些IO操作,就会发现问题了。
    多线程方法
    import  threading
    
    class Singleton:
        def __int__(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
    
    def task(arg):
        obj = Singleton.instance()
        print(obj)
    
    for i in range(13):
        t = threading.Thread(target=task, args=[i,])
        t.start()
    >>
    <__main__.Singleton object at 0x04CDC6B0>
    <__main__.Singleton object at 0x04CDC6B0>
    <__main__.Singleton object at 0x04CDC6B0>
    <__main__.Singleton object at 0x04CDC6B0>
    <__main__.Singleton object at 0x04CDC6B0>
    <__main__.Singleton object at 0x04CDC6B0>
    <__main__.Singleton object at 0x04CDC6B0>
    <__main__.Singleton object at 0x04CDC6B0>
    <__main__.Singleton object at 0x04CDC6B0>
    <__main__.Singleton object at 0x04CDC6B0>
    <__main__.Singleton object at 0x04CDC6B0>
    <__main__.Singleton object at 0x04CDC6B0>
    <__main__.Singleton object at 0x04CDC6B0>
    多线程改良版

    4.使用__new__()方法

    通过上面例子,我们可以知道,当我们实现单例时,为了保证线程安全需要在内部加入锁,我们知道,当我们实例化一个对象时,是先执行了类的__new__方法(我们没写时,默认调用object.__new__),实例化对象;然后再执行类的__init__方法,对这个对象进行初始化,所有我们可以基于这个,实现单例模式。

    import threading
    
    class Singleton:
        _instance_lock = threading.Lock()
    
        def __int__(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)
            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()import threading
    
    class Singleton:
        _instance_lock = threading.Lock()
    
        def __int__(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)
            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()
        
    >>
    <__main__.Singleton object at 0x050501F0>
    <__main__.Singleton object at 0x050501F0>
    <__main__.Singleton object at 0x050501F0>
    <__main__.Singleton object at 0x050501F0>
    <__main__.Singleton object at 0x050501F0>
    <__main__.Singleton object at 0x050501F0>
    <__main__.Singleton object at 0x050501F0>
    <__main__.Singleton object at 0x050501F0>
    <__main__.Singleton object at 0x050501F0>
    <__main__.Singleton object at 0x050501F0>
    View Code

    5.基于metaclass方式实现

    1.类由type创建,创建类时,type的__init__方法自动执行,类() 执行type的 __call__方法(类的__new__方法,类的__init__方法)
    2.对象由类创建,创建对象时,类的__init__方法自动执行,对象()执行类的 __call__ 方法
    View Code

    例子:

    class Foo:
        def __int__(self):
            pass
    
        def __call__(self, *args, **kwargs):
            pass
        
    # 执行type的 __call__ 方法,调用 Foo类(是type的对象)的 __new__方法,用于创建对象,然后调用 Foo类(是type的对象)的 __init__方法,用于对对象初始化。
    obj = Foo()
    
    obj()    # 执行Foo的 __call__ 方法   
    View Code

    元类的使用

    class SingletonType(type):
        def __init__(self,*args,**kwargs):
            super(SingletonType,self).__init__(*args,**kwargs)
    
        def __call__(cls, *args, **kwargs): # 这里的cls,即Foo类
            print('cls',cls)
            obj = cls.__new__(cls,*args, **kwargs)
            cls.__init__(obj,*args, **kwargs) # Foo.__init__(obj)
            return obj
    
    class Foo(metaclass=SingletonType): # 指定创建Foo的type为SingletonType
        def __init__(self,name):
            self.name = name
        def __new__(cls, *args, **kwargs):
            return object.__new__(cls)
    
    obj = Foo('xx')
    View Code

    单实例模式

    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)
    View Code
  • 相关阅读:
    Win10开始菜单中的天气不更新问题的解决方法
    Visual Studio 2017 的 JavaScript 调试功能的关闭
    Win10安装bash慢的解决方案
    关于 Google Chrome “Your connection is not private” 问题的处理
    关于 Inno Setup 报木马的问题处理
    Windows防火墙出站、入站相关知识总结
    关于Navicat Premium导入xlsx的问题
    关于VIM在Win10下的无意义折腾
    Mindjet MindManager 2016/2017 折腾记录
    2019腾讯前端技术大会资源TWeb
  • 原文地址:https://www.cnblogs.com/jianlin/p/9201612.html
Copyright © 2020-2023  润新知