Thursday, 14 May 2009

Singleton Vs Static Class

In the office today the subject of whether to use a singleton or a static class to implement a global object came up.

Static Class
I’ve tended to use a static class for access to a set of related global functions or resources. Particularly those that are inherently global. A good example of this might be importing a set of ‘C’ library functions:

static class SafeNativeMethods
{
internal const int ERROR_SUCCESS = 0;

[DllImport("SomeDll")]
internal static extern int InitialiseLibrary();

[DllImport("SomeDll")]
internal static extern int TerminateLibrary();
}

Those imports are static by their very nature, and it makes sense to group related functions and constants etc in one class.

Singleton
I then use a singleton for something that feels more like a traditional class than just a grouping of global stuff. That is, something that represents an actual programming object, even if it’s global and there’s only one of them.

But as I hadn’t really had pause to consider the issue for a while, I decided to do some searching to see I could find some more pearls of wisdom on the relative advantages of each approach.

Pros and Cons of The Singleton
The singleton class has bigger overheads, is more complicated to implement (but not much!), and there are some multithreaded issues to consider.

On the other hand it provides normal class functionality and hence a lot more flexibility:


  • Derivation, polymorphism etc. (And so control over the actual object that’s created).
  • You can control how and when the object is created (and destroyed). E.g. Lazy instantiation
  • You can implement interfaces. (And implement a Dispose method for cleaning up resources)
  • You can pass your singleton as a parameter to a function, which you can’t do with a static class.


Of course, most of these are really drawbacks of the static class.

Summary
I don’t think there are any hard and fast rules, but static classes are useful for wrapping fixed global resources or for more simple solutions.

If it looks like you’re ever going to want to do anything a bit more complicated you’re probably better off with a Singleton. Or maybe a combination of the two…

Useful Links
Singleton Pattern Versus Static Class in C# (dotnetperls)
Singleton (MSDN)
Implementing Singleton in C# (MSDN)
Static Classes and Static Class Members (MSDN)