24 lines
682 B
Python
24 lines
682 B
Python
# -*- coding: utf-8 -*-
|
|
from threading import RLock
|
|
|
|
class SingletonType(type):
|
|
single_lock = RLock()
|
|
|
|
def __call__(cls, *args, **kwargs): # 创建cls的对象时候调用
|
|
with SingletonType.single_lock:
|
|
if not hasattr(cls, "_instance"):
|
|
cls._instance = super(SingletonType, cls).__call__(*args, **kwargs) # 创建cls的对象
|
|
|
|
return cls._instance
|
|
|
|
|
|
class Singleton(metaclass=SingletonType):
|
|
def __init__(self, name):
|
|
self.name = name
|
|
|
|
|
|
single_1 = Singleton('第1次创建')
|
|
single_2 = Singleton('第2次创建')
|
|
|
|
print(single_1.name, single_2.name) # 第1次创建 第1次创建
|
|
print(single_1 is single_2) |