ChuannBlog

单例模式

导入文件

用类方法创建

基于__new__方法(推荐)

import time
import threading


class Foo(object):
    _instance_lock = threading.Lock()

    def __init__(self, arg):
        self.arg = arg

    def __new__(cls, *more):
        if not hasattr(cls, "_instance"):
            with Foo._instance_lock:
                if not hasattr(cls, "_instance"):
                    time.sleep(0.01)
                    setattr(cls, "_instance", object.__new__(cls))
        return getattr(cls, "_instance")


def task(arg):
    obj = Foo(arg)
    print(obj)


for i in range(10):
    t = threading.Thread(target=task, args=[i, ])
    t.start()

基于metaclass

import threading
import time


class SingletonType(type):
    _instance_lock = threading.Lock()

    def __call__(cls, *args, **kwargs):
        if not hasattr(cls, "_instance"):
            with SingletonType._instance_lock:
                if not hasattr(cls, "_instance"):
                    time.sleep(0.01)
                    setattr(cls, "_instance", super(SingletonType, cls).__call__(*args, **kwargs))
        return getattr(cls, "_instance")


class Foo(metaclass=SingletonType):

    def __init__(self, arg):
        self.arg = arg


def task():
    obj = Foo(threading.current_thread().ident)
    print(obj)


for i in range(10):
    t = threading.Thread(target=task)
    t.start()