One of the most popular creational pattern. It is used to restrict the number of instances of a type to one and so all clients use the same instance.
Consider the following class diagram :
Client creates two variables of type Singleton, s1 and s2.
The client code looks like following :
public class Client
{
Singleton s1,s2;
public void Run()
{
// s1 = new Singleton(); // new cannot be called.
s1 = Singleton.GetInstance();
s1.ID = 999;
s2 = Singleton.GetInstance();
Console.WriteLine("ID = " + s2.ID);
}
}
The output of s2.ID is '999' which shows that both s1 and s2 are referring to same instance of Singleton. Also note that default constructor has been protected.
The code for actual 'Singleton' class looks like following :
public class SingletonDownload full source code from here : Singleton Creational Pattern Source Code
{
public int ID;
private static Singleton Instance;
// Constructor is protected so that new cannot be called.
protected Singleton()
{
}
/// <returns>Singleton</returns>
public static Singleton GetInstance()
{
if (Instance == null)
{
Instance = new Singleton();
}
return Instance;
}
}
I don't believe that the Singleton class (as presented) is thread safe. To ensure that only one instance is going to be created, regardless of threads, change the Instance declaration to look like this:
ReplyDeleteprivate static readonly Singleton Instance;
The above is the .NET Framework approach to a thread-safe singleton. With a static readonly member, the internal framework guarantees that only one instance will ever be created.
If you want a traditional thread-safe approach, you'll need to introduce double check locking. Check out this article from my colleague, Mark Townsend:
http://msdn.microsoft.com/en-us/library/ms954629.aspx