The singleton pattern basically involves a class that only allows a single
instance of itself to be instantiated.
The first snippet gives a basic (but bad) idea on how to create a singleton.
public sealed class Singleton
{
static Singleton _instance = null;
private Singleton()
{
Console.WriteLine("Instance Created");
}
public static Singleton Instance
{
get
{
if (_instance == null)
{
_instance = new Singleton();
}
return _instance;
}
}
}
A few notes on the previous snippet:
Seal this class in order to prevent derived classes to break the pattern.
Create a private constructor in order to prevent instantiation of the class.
Return an instance of the class via static property.
There is however a fundamental problem with the preceding snippet which become apparent
as soon as we introduce threading into the equation, observe:
class Program
{
static void Main()
{
for (int i = 0; i < 10; i++)
{
Thread thread = new Thread(new ThreadStart(ThreadMain));
thread.Start();
}
}
static void ThreadMain()
{
Thread.Sleep(500);
try
{
Singleton s = Singleton.Instance;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
As soon as we use the singleton (in the first snippet) within multiple threads, you will notice multiple
objects being instantiated e.g. "Instance Created" gets written to the console multiple times - in the case of
a real singleton its supposed to only write to the console once.
In the following snippet we solve the threading issue by using a lock:
public sealed class Singleton
{
private static volatile Singleton instance;
private static object locker = new Object();
private Singleton()
{
Console.WriteLine("Instance Created");
}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (locker)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}
By running the preceding snippet in the threading snippet, you will notice only one "Instance Created" message.
A few notes on the previous snippet:
Use volatile in order to ensure that assignment to the variable completes
before we access it.
It is however possible to achieve thread-safety without a lock, by relying on the CLR (common language runtime) to handle initialization - the
following method is the preferred approach to creating a Singleton in .NET.
public sealed class Singleton
{
public static readonly Singleton Instance = new Singleton();
static Singleton() { }
private Singleton()
{
Console.WriteLine("Instance Created");
}
}
Few notes:
Set the static instance variable to readonly in order to prevent any changes to be
made to the instance as soon as its created.
Add a static constructor with regards to lazy initialization e.g. beforefieldinit flag. (the static constructor initializes as soon as we access a static member - which in this case postpone the creation of the singleton instance)
Terminology:
Lazy Initialization
Refers to a performance optimization that postpones the need to create/instantiate an object
until its really needed - by contrast the default initialization for objects in .NET is called
eager initialization - happens immediately.
Note that all of the Singleton snippets in this post make use of lazy initialization.
In the .NET 4.0 framework Microsoft added the Lazy Class to provide developers with a simple way
to use lazy initialization in their code, observe the following .NET 4.0 Singleton:
public sealed class Singleton
{
private static readonly Lazy<Singleton> _instance = new Lazy<Singleton>(() => new Singleton());
private Singleton() { Console.WriteLine("Instance Created"); }
public static Singleton Instance
{
get
{
return _instance.Value;
}
}
}
Thanks Andre, hopefully soon I will have a complete list of examples available on all design patterns - started working on a post regarding the factory pattern.
August 11, 2010 by André van Coller
Here is a link that might be useful for more design pattern examples http://patterns.cs.up.ac.za/
The youtube video very funny :)
August 11, 2010 by Christoff Truter
Thats why I always told you that you've got a great lastname for a programmer ;)
August 11, 2010 by Christoff Truter
Thanks Andre, hopefully soon I will have a complete list of examples available on all design patterns - started working on a post regarding the factory pattern.