单例模式(Single Pattern)
Ensure a class has only one instancem, and provides a global point to access to it.
In [8]:
import threading
import time
class Singleton(object):
def __new__(cls,*args,**kw):
if not hasattr(cls,'_instance'):
orig=super(Singleton,cls)
cls._instance=orig.__new__(cls,*args,**kw)
return cls._instance
In [6]:
class Bus(Singleton):
lock=threading.RLock()
def sendData(self,data):
self.lock.acquire()
time.sleep(3)
print('Sending single data...',data)
self.lock.release()
class VisitEntity(threading.Thread):
my_bus=''
name=''
def getName(self):
return name
def setName(self,name):
self.name=name
def run(self):
self.my_bus=Bus()
self.my_bus.sendData(self.name)
for i in range(3):
print('Entity %d begin to run...'%i)
my_entity=VisitEntity()
my_entity.setName('Entity_'+str(i))
my_entity.start()
In [ ]: