[Tutor] singleton pattern
Roeland Rengelink
r.b.rigilink@chello.nl
Fri, 18 May 2001 19:43:09 +0200
alan.gauld@bt.com wrote:
>
[snip]
> > * the SingletonFactory
> >
> > class SingletonFactory:
> > singleton = None
> > def __call__(self):
> > if SingletonFactory.singleton is None:
> > SingletonFactory.singleton = Singleton()
> > return SingletonFactory.singleton
>
> And this is what I was doing in my second post except
> that I was allowing multiple Factories to be created
> each one managing a singleton instance of the class
> specified in the ctor. But I then moved the actual
> construction of the singleton into the makeInstance
> method and used an exception to pass back the actual
> singleton instance rather than fake access thru'
> the Factory class.
>
> > >>> SF = SingletonFactory()
> > >>> x = SF()
> > >>> y = SF()
> > >>> id(x) == id(y)
> > 1
>
> I guess my question is whether it wouyld be easier to
> assign the instance attribute directly to x,y:
>
> >>> x = SF().instance
> >>> y = SF().instance
>
that's what
>>> x = SF()
>>> y = SF()
allready do
Remember SF is an instance of SingletonFactory, SF().instance makes no
sense
x = SF()
is equivalent to
x = SF.__call__()
which is equivalent to
x = SF.singleton # if SF.singleton != None)
or
SF.singleton = Singleton() # if SF.singleton == None
x = SF.singleton
> And also what happens using this model if we create more than one
> SignletonFactory instance:
>
> SF = SingletonFactorty()
> MF = SingletonFactorty()
> x = MF()
> y = SF()
>
SF.singleton == MF.singleton
That's why I assigned to SingletonFactory.singleton, rather than
self.singleton
SingletonFactory in this sense behaves like a singleton itself (i.e.
different ids, but identical state)
> are x and y now pointing at the same object?
>
yes
Have fun,
Roeland
--
r.b.rigilink@chello.nl
"Half of what I say is nonsense. Unfortunately I don't know which half"