单例模式

设计模式是一种编程思想,与具体编程语言无关,在不同的编程语言中有不同的表现形式。这种编程思想的意义比用某种编程语言实现某种设计模式更重要。不能为了设计模式而设计模式,更不能在一种编程语言中生搬硬套另一种编程语言对某种设计模式的具体代码实现。


 单例模式:由于Java不支持全局变量,所以需要一种解决方案以满足全局变量的需求,单例模式就是一种很好的选择。对于已经支持全局变量的语言(如Python)单例模式并非必须。

 

单线程时的代码实现:

class A:
    def __new__(cls):
        if not hasattr(cls,'_instance'): # 不能用__instance
            # cls._instance=super().__new__(cls)
            cls._instance=object.__new__(cls)
        return cls._instance

a1=A()
a2=A()
print(id(a1))
print(id(a2))

 线程安全的代码实现:

from threading import Thread,Lock
from time import sleep


class A:
    __lock=Lock()
    def __new__(cls):
        with cls.__lock:
            if not hasattr(cls,'_instance'):
                sleep(1)
                cls._instance=object.__new__(cls)
        return cls._instance

def f():
    print(id(A()))

t1=Thread(target=f)
t2=Thread(target=f)
t1.start()
t2.start()

 实际Python开发中的单例模式根据业务场景有各种实现方案,如import 模块、__init__.py等都具有单例模式思想。

object.__new__(cls)使得Python无真正意义上的单例,此法不会调用__init__()

posted @ 2020-10-21 21:02  xiongjiawei  阅读(94)  评论(0编辑  收藏  举报