Tuesday, January 25, 2005

Few notes on singletons

No class should explicitly reveal that it has implemented the singleton pattern.

If you want access to an instance of a class, whether it's a singleton or not is irrelevant. From the sender side, as long as you get an instance when you send #new, why should you care if it is a singleton or not? Therefore, you should just send #new to the class. How the class implements #new is the class' business.

Any method like #default, #singleton, #theOne, etc makes the class reveal details that should be kept private. There should be no such implementation-revealing method.

From the implementation side, the singleton should be remembered in a class instance variable. My favorite class instance variable name for singletons is 'current'. I use accessors, therefore the class should have #current and #current: accessors, preferably in a private category. #new should send these accessors.

No comments: