Singleton Refactorings

Moved from SingletonPattern

I find that singletons frequently appear in solutions which are the SimplestThingThatCouldPossiblyWork. This means that there are cases where they no longer work, and you have to have effective means of refactoring so that the singleton property is no longer used.

There are a number of refactorings involving singletons which didn't make it into RefactoringImprovingTheDesignOfExistingCode. Like most refactorings, these can be run forwards or backwards. My candidates include:

AbstractSingleton?. As above, this is separating the interface of a singleton from the implementation, and make the instance function return the interface.

AggregateSingletonObjects?. Collecting a number of related singleton objects and making them members of a compound object, which is itself singleton. Static functions can also become member functions of the compound object. Done correctly, this is a first class opportunity to identify a good (by which I mean cohesive and well defined) class, and I have frequently come across this in legacy code.

DelegateSingleton?. Starting with an object which is accessed via a singleton instance, make it accessible in other ways, such as by passing it as a parameter, creating a proxy for it, or by delegating to some known object the task of finding it. At the bottom layers where objects should know little about their environment (so that they can be used in different environments) I tend to pass the former singleton as a parameter; higher up, where objects tend to cluster for some group purpose, I make one of them responsible for knowing which object to use.

-- AndrewParle


EditText of this page (last edited August 20, 2002) or FindPage with title or text search