Singleton vs Static Class

An entry about c# 3.0 Publication date 4. April 2007 15:49

The Singleton Pattern is probably the single most used design pattern among todays developers. In .NET, implementing it is very simple:

public sealed class MySingleton
{
public static readonly MySingleton Instance = new MySingleton();
private MySingleton()
{ }
}

We don't have to worry about synchronisation and lazy-loading issues - the JIT will make sure it is only ever initialized when (and if) a method accesses the Instance property, and the .NET framework also guarantees thread safety on static type initialization.

For a more thorough discussion on implementing a Singleton in .NET, there is a great article on MSDN on the subject. What I wanted to discuss in this post however, was how to decide between using a Singleton and a static class. To answer that question, we first need to know what the differences between the two are:

On a lower level, there is a difference in how the CLR loads a Singleton (assuming it has been implemented as previously described) and a static class; while a Singleton is properly lazy-loaded, a static class is loaded by the CLR when the containing namespace is loaded.

More importantly though, the Singleton pattern is defined as ensuring that there exists one and only instance of a given object, with a global point of access to it. A static class on the other hand, has no instance - essentially it is a sealed class with only static members and a private constructor. In many languages, like Java, this is how we would define a static class - but in .NET 2.0 we can explicitly mark a class as static. The compiler can then guarantee to us that the class will never be instantiated, inherited or contain instance members.

But what does this mean? It tells us that a static class is by definition state-less - it has no instance for which to define any states. A singleton then, can be used to represent the state of some singular entity - the Registry, a configuration file, a thread pool etc. Static classes on the other hand, are great for grouping together a set of methods that need not be associated with any particular instance of an object. System.Math is an example of when to use a static class - it is a collection of methods that can be used to perform calculations like finding the cosine of an angle, the logarithm of a number and so forth, and no method in the class cause any side effects outside of its scope by being called. This is different from removing a key from the Registry, which could potentially cause a later call to read a value from the Registry to fail.

Note that even though the Registry class in .NET is also a static class, it uses Singletons internally to manage the state of each of the main RegistryKeys, and thus is an interresting example of how static classes and Singletons can work together to provide an intuitive API.

Not everyone agrees that static classes have their use however (and while that particular comment is in relation to Java, the concepts are the same for any object oriented language), and in the end it pretty much comes down to personal preference and coding style. But knowing both concepts and how they differ may help you in arguing for why you've chosen a particular solution when your co-workers challenge you on it during a code review :)

Currently rated 4.0 by 10 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Comments

Powered by BlogEngine.NET 1.4.5.0

Welcome!

My name is Fredrik Kalseth, and this is my blog - thanks for visiting! I am fortunate enough to work with what I love for a living, and this blog is essentially the biproduct of that.

I work as a senior consultant for Capgemini, and am also an active participant in the Norwegian .NET community, as an avid attendee but also as a speaker (most recently at NNUG and MSDN Live).

As a developer, I have a wide circle of interest. My primary passion is for agile, test-driven development, with focus on best practices and clean code. That said, I also love to work on the frontend, especially with web development.

On Twitter? My handle is fkalseth. On LinkedIn? I`m there too.


Disclaimer

This is a personal blog; any opinions expressed here are my own and do not necessarily reflect those of my employer. All content herein is my own original creation, and as such is protected by copyright law. Unless otherwise stated, all source code posted on this blog is freely usable under the Microsoft Permissive License.

What Readers Talk About

Comment RSS