Python Tutorial

Monday, September 17, 2012

Design pattern in python: Singleton pattern

Python singleton design pattern example:
For implementing Singleton pattern we need to override the "__new__" method of class

class MyClass:
 def __init__(self):
  self.numA = 5
  self.numB = 10
 def getNumA(self):
  return self.numA

 def getNumB(self):
  return self.numB

 def setNumA(self, v):
  self.numA = v

 def setNumA(self, v):
  self.numB = v

 def toString(self):
  return "A:",self.numA,"B:",self.numB

_singleton = None

def get_instance(cls = MyClass):
 global _singleton
 if _singleton is None:
  _singleton = cls()
 return _singleton

if __name__=='__main__':
 print "Main output"

 a = get_instance()
 print a.toString()
 print a.toString()

 b = get_instance()
 print b.toString()

Main output
('A:', 5, 'B:', 10)
('A:', 5, 'B:', 15)
('A:', 5, 'B:', 15)


Post a Comment