python3 类的单例模式


class Singleton():
    __instance = None

    def __init__(self):
        print("我是init方法.")

    def __new__(cls):
        if not Singleton.__instance:
            Singleton.__instance = object.__new__(cls)
        return Singleton.__instance


obj1 = Singleton()
obj2 = Singleton()
print(id(obj1), id(obj2))

执行结果:

我是init方法.
我是init方法.
42790640 42790640

 

使用锁的单例模式

from threading import Lock


l = Lock()


class Singleton():
    __instance = None

    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            l.acquire()  # 保证安全
            cls.__instance = object.__new__(cls)
            l.release()  # 保证安全
        return cls.__instance

    def __init__(self):
        pass


s1 = Singleton()
s2 = Singleton()
print(s1, s2)  # 内存相等

 执行结果:

<__main__.Singleton object at 0x000000000292EF28> <__main__.Singleton object at 0x000000000292EF28>

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM