单例模式(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()


Entity 0 begin to run...
4533282352
Entity 1 begin to run...
4533282800
Entity 2 begin to run...
4533282632
Sending single data... Entity_0
Sending single data... Entity_1
Sending single data... Entity_2

advantage

  • Because of only one instance in global environment, it can save memory.
  • Because of the only one access point, it can be used to concurrent.
  • The only one Instace can store in memory, avoiding creating instance.

Disadvantage

  • Difficulty for expansion
  • revolt the Single Responsibilyt Principle
  • Unfriendly unit test

In [ ]: