Python设计模式——单例模式(Singleton Pattern)

import threading

lock = threading.Lock()


class Singleton:
    __uniqueInstance = None

    def __init__(self):
        pass

    @classmethod
    def getInstance(cls):
        lock.acquire()
        if cls.__uniqueInstance is None:
            cls.__uniqueInstance = Singleton()
        lock.release()
        return cls.__uniqueInstance


if __name__ == '__main__':
    a = Singleton.getInstance()
    b = Singleton.getInstance()
    print(a is b)
    print(id(a), "  ", id(b))

 

你可能感兴趣的:(Python设计模式)