zoukankan      html  css  js  c++  java
  • 单例模式4种方式

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

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

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

    1.使用模块

    可以参考自定义增删改查组件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()

    2.使用 __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)

    加上锁

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

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

    a.不能支持多线程的单例模式

    class Singleton(object):
    
        @classmethod
        def instance(cls,*args,**kwargs):
            if not  hasattr(Singleton,'_instance'):
               
                Singleton._instance=Singleton()
            return Singleton._instance
    
    
    a=Singleton.instance()
    b=Singleton.instance()
    print(a==b)#True

    但是我们加上多线程试试

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

    结果:

    D:virtualenvenvsvuedjangoScriptspython.exe D:/test/flaskTest/flaskpro3/单例模式/类.py
    <__main__.Singleton object at 0x0000022E579C6E80>
    <__main__.Singleton object at 0x0000022E579AB898>
    <__main__.Singleton object at 0x0000022E579EC6A0>
    <__main__.Singleton object at 0x0000022E579DB1D0>
    <__main__.Singleton object at 0x0000022E579EC5C0>
    <__main__.Singleton object at 0x0000022E579D1FD0>
    <__main__.Singleton object at 0x0000022E579D9C50>
    <__main__.Singleton object at 0x0000022E579C6F60>
    <__main__.Singleton object at 0x0000022E579D1EB8>
    <__main__.Singleton object at 0x0000022E579DB2B0>
    
    Process finished with exit code 0

    b.解决上面存在的问题,实现支持多线程的单列模式:

    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()

    结果:

    D:virtualenvenvsvuedjangoScriptspython.exe D:/test/flaskTest/flaskpro3/单例模式/类.py
    <__main__.Singleton object at 0x000001BADB56F320>
    <__main__.Singleton object at 0x000001BADB56F320>
    <__main__.Singleton object at 0x000001BADB56F320>
    <__main__.Singleton object at 0x000001BADB56F320>
    <__main__.Singleton object at 0x000001BADB56F320>
    <__main__.Singleton object at 0x000001BADB56F320>
    <__main__.Singleton object at 0x000001BADB56F320>
    <__main__.Singleton object at 0x000001BADB56F320>
    <__main__.Singleton object at 0x000001BADB56F320>
    <__main__.Singleton object at 0x000001BADB56F320>
    
    Process finished with exit code 0

    问题:

    创建实例只能调用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)
  • 相关阅读:
    模板语法 DTL(Django Template Language )
    django基础
    day1,基本标签总结
    聚合函数
    day1
    day 3 定时任务
    day 4 tar
    day 6
    day1 mysql
    day 6
  • 原文地址:https://www.cnblogs.com/lifei01/p/10672245.html
Copyright © 2011-2022 走看看