[Tutor] singleton pattern

alan.gauld@bt.com alan.gauld@bt.com
Fri, 18 May 2001 17:32:37 +0100


> > Acerge wrote:
> Except that self.__class__.instance works with subclasses of
> SingletonInstance but SingletonInstance.instance does not.  

OK, fair point.
I was making a single factory class that could generate 
singletons of any type but you are making a class which 
can be subclassed, fair enough.

> > >       self.__class__.instance = klass() # make the instance
> ... 
> Pointing to the same instance is not a necessary condition for the
> the problem of a singleton class.  It might be how you think 
> it should work, but nothing in the functionality defined 
> even hints to "Class() is Class()" as a tautology.

Indeed, but surely "instance is instance" is?

> The above does not "ensure that calls to SingletonInstance 
> produce a new instance of klass".  

Yes, looking again I see that in fact if you try to pass 
a different class in subsequent calls it will be ignored. 
(In fact its ignored regardless of what you pass in!)

> >>> aspam = SingletonInstance(Spam)
> >>> bspam = SingletonInstance(Spam)
> >>> aspam.__class__.instance is bspam.__class__.instance
> 1

> the 'instance' class member will always be the first instance
> of the klass given in the first call 

Exactly so, that was the bit I missed first time around.

> and that the two instances behave identically.

Since they delegate everything to the underlying 
singleton instance, correct. This is the tie in 
to Roelands post about the two techniques for 
generating singleton behaviour. I was trying 
to build a generic singleton factory, you are 
building a singleton wrapper. Because the ctors 
looked similar I tried to apply a factory metaphor 
to your wrapper class....
 
> The goal, and requirement, of a singleton class 
> is that an instance from a class _behaves identically_ 
> to any other instance of that class,

Agreed.

> not that only one instance can be created.  

Agreed, one instance is only one way of implementing that 
behaviour.

> Mine was not the answer to the original question and
> I didn't attempt to make it such, 

I think thats what confused me. I assumed it was an attempt 
to answer the original question.

> overly-complicated, abortive method at instance creation.

That'd be my original pseudo-code then :-)

Alan g