[Tutor] What are "singletons" good for?

Lie Ryan lie.1296 at gmail.com
Sat Sep 18 22:03:33 CEST 2010


On 09/19/10 02:50, Knacktus wrote:
> Hey all,
> 
> the usual explanation for the usage of a Singleton goes like this:
> 
> "Use a singleton if you want to make sure, that only one instance of a
> class exists."
> 
> But now I ask myself: Why should I call the constructor of a class more
> than once if I only want one instance?
> After all, I decide in my code when to create an instance or when to
> pass an existing instance around.

The guarantee.

If you're writing a module that may be used by two or more modules, that
may be used by a script. A logger module is a good example; if your
script imports two modules, and both modules import the same logger
module and instantiate their own version of loggers, then it is
difficult to coordinate the logging of those two modules. If instead the
logger class is a Singleton, then the user of logger modules doesn't
need to care about any other modules using the same logger module, since
they will create an instance when needed or get the existing logger when
someone else already made one.

A configuration module is another good example. It is a common idiom in
python to import a .py script for configuration purpose. The benefit of
this is that the config file basically becomes a truly global variable
(python does not have a true global variable).

> What's the point? Is it the spared typing when instanciating a lot of
> View classes (I wouldn't need to pass the session to the constructor).
> Or are there some more advantages (instead of passing the same instance
> aorund)? Also, what would you guys consider as disadvantages?

Disadvantage? compared to what?



More information about the Tutor mailing list