[Tutor] singleton pattern
alan.gauld@bt.com
alan.gauld@bt.com
Fri, 18 May 2001 16:13:31 +0100
> Now, Python (or C++ for that matter) doesn't return
> a pointer from the constructor.
Correct thats why my pdseudo code attempt was broken.
> (Not without completely unpythonic namespace hackery)
And we don't wanna go there :-)
> * the SingletonWrapper
>
> class SingletonWrapper:
> singleton = None:
> def __init__(self):
> if SingletonWrapper.singleton is None:
> SingletonWrapper.singleton = Singleton()
Which I think is what Michael was trying to do but
failing(I think) because instead of assigning
Singleton() he was assigning a class passed in
to the constructor... Thus multiple instances of
different classes would result.
> SingletonWrapper is not itself a singleton, but of Singleton
> there will be only one instance, so:
>
Correct.
> * 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
And also what happens using this model if we create more than one
SignletonFactory instance:
SF = SingletonFactorty()
MF = SingletonFactorty()
x = MF()
y = SF()
are x and y now pointing at the same object?
[ Boy, I hope I get my own PC back soon, being without
a python install at work is killing me! :-) ]
> change SingletonWrapper or SingletonFactory themselves into
> singletons, will lead rather soon into infinite regress.
Correct, you need a factory somewhere, whether it be a
callable class or a specific factory is the decision.
Alan g.