Differences between revisions 4 and 5
Revision 4 as of 2003-11-17 22:10:38
Size: 758
Editor: yermat
Comment:
Revision 5 as of 2003-11-17 22:11:21
Size: 827
Editor: yermat
Comment:
Deletions are marked like this. Additions are marked like this.
Line 5: Line 5:
See also http://c2.com/cgi/wiki?PythonSingleton See also http://c2.com/cgi/wiki?PythonSingleton and http://www.python.org/workshops/1997-10/proceedings/savikko.html

Singleton

See also http://c2.com/cgi/wiki?PythonSingleton and http://www.python.org/workshops/1997-10/proceedings/savikko.html

classmethod


pro

  • You can use both as simple class or as a singleton.
  • You do not need to write code for each class you want to act as singleton.


cons

   1 # Code is Public Domain.
   2 class Singleton:
   3     _singleton = None
   4     
   5     def getSingleton(cls):
   6         if not Singleton._singleton:
   7             Singleton._singleton = cls()
   8         return Singleton._singleton
   9 
  10     getSingleton = classmethod(getSingleton)
  11 
  12 
  13 class Test(Singleton):
  14     def test(self):
  15         print self.__class__,id(self)
  16 
  17 
  18 t1 = Test.getSingleton()
  19 t2 = Test.getSingleton()
  20 
  21 t1.test()
  22 t2.test()

PatternProgramming (last edited 2008-11-15 13:59:47 by localhost)

Unable to edit the page? See the FrontPage for instructions.