Simplify Singleton Pattern

The Singleton Pattern is well known to avoid multiple instances of a class. Whenever a Singleton is useful or not – some people say that Singletons are the face of evil – the implementation is really straightforward:

public class MySingleton
{
	private static readonly object mutex = new object();
	private static MySingleton instance;

	private MySingleton() { }

	public static MySingleton Instance
	{
		get
		{
			lock (mutex)
			{
				if (instance == null)
				{
					instance = new MySingleton();
				}
			}
			
			return instance;
		}
	}
}

Jon Skeet, Google employee, C# MVP and heavy Stackoverflow user, mentioned a much simpler implementation, which works pretty well.

public class MySingleton
{
	private static readonly MySingleton instance = new MySingleton();

	static MySingleton() { }

	private MySingleton() { }

	public static MySingleton Instance
	{
		get { return instance; }
	}
}

Before I read this code my assumption was that a static class or a variable would be initialized when the program starts. Unfortunately, I was wrong. The static variable will be initialized right before the first access. The .NET Framework takes care of all other parts, especially the thread safety, so a mutex is not longer necessary.

To proof this lazy initialization I added some console outputs that shows the exact order of initialization and usage. To make things simpler I used a Unit test as environment.

public class MySingleton
{
	private static readonly MySingleton instance = new MySingleton();

	static MySingleton() { }

	private MySingleton()
	{
		Console.WriteLine("MySingleton constructor");
	}

	public static MySingleton Instance
	{
		get { return instance; }
	}

	public void Do()
	{
		Console.WriteLine("Do someting");
	}
}

[TestFixture]
public class UseSingleton
{
    [Test]
	public void UseMySingleton()
    {
	    Console.WriteLine("Using start");
		MySingleton singleton1 = MySingleton.Instance;
		singleton1.Do();
	    MySingleton singleton2 = MySingleton.Instance;
		Console.WriteLine("Using end");

		Assert.AreSame(singleton1, singleton2);
    }
}

The output window shows the order:

TestResult

No rule without exceptions: This is not as lazy as the first implementation. If you have static members other than Instance, the first reference to those members will involve creating the instance. This laziness is only guaranteed by .NET, because of the static constructor. Otherwise the type will be marked by the C# compiler with a special flag called beforefieldinit, with the result that laziness if off the table.

To bypass this behavior Jon suggests another implementation with a nested class.

public class MySingleton
{
	private static class MySingletonHolder
	{
		internal static readonly MySingleton instance = new MySingleton();

		static MySingletonHolder() { }
	}
		
	private MySingleton()
	{
		Console.WriteLine("MySingleton constructor");
	}

	public static MySingleton Instance
	{
		get { return MySingletonHolder.instance; }
	}

	public void Do()
	{
		Console.WriteLine("Do someting");
	}
}

Jon wrote an article about the different implementations of the Singleton Pattern and I highly recommend reading it:
http://www.csharpindepth.com/Articles/General/Singleton.aspx

Advertisements
This entry was posted in C#, Development and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s