Implementing the Gang of Four Singleton Pattern in Microsoft’s C# .NET language is nearly identical to its Java implementation. The Singleton Pattern (as definied by the Gang of Four in 1995) is to “ensure a class only has one instance, and provide a global point of access to it.”
The idea behind the Singleton pattern is that there can only be one unique object of the class in existence at any one time. To make this possible we must make the constructor private and instead create a public “get” accessor for the Instance reference that controls access to the constructor, returning a new object if none exists or returning the already instantiated object if one does.
Here we have an example of the simplest possible Singleton class which I call, Singleton. It has only those methods absolutely necessary for the pattern and one console print statement in the constructor so that we can easily see when the constructor is called. I have opted to include Singleton and TestSingleton, its testing harness, in a single file. This allows me to easily demonstrate how to create the Singleton pattern and how to instantiate a Singleton object from outside the class.
TestSingleton.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SingletonPattern
{
class TestSingleton
{
static void Main(string[] args)
{
Console.WriteLine("Calling First Instance: ");
Singleton mySingleton = Singleton.Instance;
Console.WriteLine("Calling Second Instance: ");
Singleton myOtherSingleton = Singleton.Instance;
}
}
public class Singleton
{
private static Singleton instance;
private Singleton()
{
Console.WriteLine("Singleton Constructor Called");
}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
Microsoft has a great article discussing the Singleton Pattern and its common variations as they pertain to the C# language in the MSDN Patterns and Practices Developers Center – Implementing Singleton in C#.
Also see: Sheep Guarding Llama Singleton Pattern in Java