Python——23种设计模式

单例模式:

为了确保在单例模式下,创建的每一个线程都是在同一块内存空间中,这样做的目的就是为了节省重复性的线程所导致的占用内存空间。

不加单例模式的实例化效果:

class SingLeton(object):
    pass

obj1 = SingLeton()
print(obj1)  #<__main__.SingLeton object at 0x00000167A41C7700>
obj2 = SingLeton()
print(obj2)   #<__main__.SingLeton object at 0x00000167A41C7C10>

使用单例模式后:

class SingLeton(object):
    instance = None
    def __new__(cls, *args, **kwargs):
        if not cls.instance:
            cls.instance = object.__new__(cls)
        return cls.instance
obj1 = SingLeton()
print(obj1)   #<__main__.SingLeton object at 0x00000167B0277C10>
obj2 = SingLeton()
print(obj2)   #<__main__.SingLeton object at 0x00000167B0277C10>

线程+锁的单例模式

 

from threading import Thread,Lock

class SingLeton(object):
    instance = None
    lock = Lock()
    def __new__(cls, *args, **kwargs):
        with cls.lock:
            if not cls.instance:
                cls.instance = object.__new__(cls)
        return cls.instance
for i in range(10):
    print(SingLeton())

 

  

 

posted @ 2020-05-14 16:25  新兵蛋Z  阅读(447)  评论(0)    收藏  举报