22 lines
595 B
Python
22 lines
595 B
Python
|
|
from threading import RLock
|
||
|
|
|
||
|
|
class Singleton(object):
|
||
|
|
single_lock = RLock()
|
||
|
|
|
||
|
|
def __init__(self, name):
|
||
|
|
if hasattr(self, 'name'):
|
||
|
|
return
|
||
|
|
self.name = name
|
||
|
|
|
||
|
|
def __new__(cls, *args, **kwargs):
|
||
|
|
with Singleton.single_lock:
|
||
|
|
if not hasattr(Singleton, "_instance"):
|
||
|
|
Singleton._instance = object.__new__(cls)
|
||
|
|
|
||
|
|
return Singleton._instance
|
||
|
|
|
||
|
|
single_1 = Singleton('第1次创建')
|
||
|
|
single_2 = Singleton('第2次创建')
|
||
|
|
|
||
|
|
print(single_1.name, single_2.name) # 第2次创建 第2次创建
|
||
|
|
print(single_1 is single_2) # True
|