[Tutor] singleton pattern
alan.gauld@bt.com
alan.gauld@bt.com
Fri, 18 May 2001 11:43:38 +0100
Acerge wrote:
> class SingletonInstance:
> instance = None # class member for the singleton instance
> def __init__(self, klass):
> if self.__class__.instance is None:
OK, I've now read the docs and had a play.
This is solving a slightly different problem, I think.
The self.__class__.instance is only a convoluted way of writing
SingletonInstance.instance - I think the latter is clearer.
> self.__class__.instance = klass() # make the instance
This is setting the instance attribute of the SingletonInstance
class to an instance of the manufactured class. I'm not sure how
this gives us a singleton structure? It will ensure that
calls to SingletonInstance produce a new instance of klass
and assign it to the class variable, but for a singleton we
want to ensure that calls to the constructor return a pointer
to *the same* instance.
Thus:
foo = SingletonInstance(MyFileClass)
and
bar = SingletonInstance(MySocketClass)
should make foo and bar reference the same instance (but,
in this case, set the internal instance variable
to a new class reference)
Whereas what we seem to have is foo referncing an instance
of SingletonInstance with a reference to MyFileClass and able
to access the attributes of MyFileClass instance via foo.
And bar referencing a different instance of SingletonInstance
with a reference to MySocketClass. But does the class variable
of both foo and bar now reference MySocketClass. In which case
foo is going to exhibit some weird behaviour!
This is interesting but I'm not sure its either a Factory
or a Singleton. I think I'm maybe missing something?
> years ago. IMO, Factory classes are not something that new
> programmers(reading the tutor list to learn) should be grappling.
Depends on whether they are new programmers or new Pythoneers.
If the latter they may have experience of Factories and
Singletons from C++, ObjectiveC, Smalltalk etc.
Alan G.