[Tutor] singleton pattern

D-Man dsh8290@rit.edu
Wed, 16 May 2001 11:36:15 -0400


On Wed, May 16, 2001 at 10:26:32AM -0400, Benoit Dupire wrote:

The thing to remember about Python is that unlike Java you are not
forced to put everything inside a class.  Somethings don't really
belong inside a class.  Static methods are one of those things.  They
belong in a module instead.  There is no way to have static methods in
a class in python, but you have modules instead. 

<...>
| which is a nice solution (not from me ! :o) )

It is a nice solution -- you can only have one instance of that class
and it is stored in the module.

| The problem is that i already have a __call__ method implemented in my
| Factory class.

How is this a problem?  Your __call__ method works on an _instance_ of
the class, not the class itself.

| Python unfortunately does not support overriding...

It does.  It doesn't support overloading.



Here are a couple ways to implement the singleton pattern:

######## Factory.py -- the "Factory" module ##########

class _Factory :
    def create_object( self ) :
        pass

factory_instance = _Factory()
del _Factory # optional,  alternatively use the same name as in the
             # above example then the name will be rebound

##############################

 From the client side one would use the following code :

import Factory

an_object = Factory.factory_instance.create_object()
print an_object



Here is an alternative to use if you are a fan of functions and would
rather not use public module variables :

######## Factory.py ##########

class _Factory :
    def create_object( self ) :
        pass

_instance = None

def get_instance() :
    if _instance is None :
        _instance = _Factory()
    return _instance

####################

The client would look like :

import Factory

an_object = Factory.get_instance().create_object()
print an_object



Don't be afraid to use modules when they are more apropriate than a
class <grin>.  (I know -- it is a different way of thinking.  It has
taken me a while to get used to it having learned from class-based OO
lanauages first.)

-D