Monday, June 21, 2004

Implementing a Well behaved Singleton - 1

Singleton is one of the simplest design patterns. It also the one most abused. I have seen developers replace a global variable with a signleton object and argue that since its a design pattern, its good without really looking at the intent of the pattern and the effects.

What do i mean by a Well Behaved Singleton ? A well behaved Singleton will have following characteristics.
1. Construction is trasparent to the user(at start of program or on demand).
2. If construction of the singleton depends on some other object being initialized first, then the implementation should ensure that constructor sequence is correct under any circumstances.
3. Destruction is trasparent to the user.
4. If some other object (esp. destruction of some other object) depends on Singleton, timing and sequence of destuction of Singleton should be correct in any circumstances.
5. Single instance is ensured by the implementation. It should be impossible to create a second instance. If the user tries to create a second instance, the implementation should give an error (e.g compilation error, assertion failure etc)
6. All assumptions are made explicit.

Assuming that you understand intent of pattern and want to implement a singleton, there are many ways to achieve it, depending on your needs. First Lets look at major considerations for how to implement a Singleton.

1. Do you anticipate a need to create a derived class which is also a singleton ?
2. Does the initialization of a Singleton object depend on some other object being already initialized ?
3. Does some other object (e.g. other singleton) depend of Singleton object being initialized first ?
4. Does the destruction of a Singleton object depends on existance of some other object ?
5. How Are you ensuring destruction of Singleton ?

In this series I plan to look at some ways of implementing Singleton, look at pros/cons of them and see how well behaved they are.

No comments: