[Q] Why Squeak don't have a Singleton class ?

R. Clayton rvclayton at acm.org
Sat Dec 3 14:56:27 UTC 2005


  We could have:
  
  Object subclass: #Singleton
     instanceVariableNames: ''
     classVariableNames: 'UniqueInstance '
     poolDictionaries: ''
     category: 'Kernel-Classes'
     
  current
     UniqueInstance ifNil: [UniqueInstance := Singleton basicNew].
     ^UniqueInstance
     
  new
     self error: 'Use current to get an instance of Class ' , self name

I'm not understanding how this would work as a superclass.  current should
return the object of one of Singleton's child classes, not the object of the
Singleton class (which shouldn't exist anyway given that Singleton should be an
abstract class).  Because I don't know of a simple way of calling down an
inheritance hierarchy, I'm thinking that Singleton>>current can best be
implemented as a subclass responsibility, which runs counter to factoring
common code in a superclass (or suggests that there may not be a useful amount
of factorable common code among singleton implementations).

  In case not, why not

Assuming the previous objection can be dealt with, the need for a class
variable per singleton class causes a problem.  For example, if I make both
SymbolTable and TypeTable subclasses of Singleton, then the return value for
both SymbolTable>>current and TypeTable>>current is set by whichever of
SymbolTable>>current or TypeTable>>current is called first, an unhappy event
for the current method called second.

There's a few ways to fix this.  One is move UniqueInstance down into the child
classes too, at which point we can end the discussion as to why there's no
Singleton class in Squeak (assuming there isn't one; I don't know for sure).
Another is to implement a registry of Singletons (Design Patterns, page 130),
which is a loss if you're interested in making code simpler and smaller.



More information about the Squeak-dev mailing list