Singleton Pattern
The singleton pattern is a software design pattern that is used to restrict instantiation of a class to one object. This is useful when we require exactly one object of a class to perform our operations. In this pattern we ensure that the class has only one instance and we provide a global point of access to this object.The singleton pattern can be implemented in C# by the use of static method, which provides a global point of access to a singleton object. We create a static volatile object of the class which serves as a single instance for the class. Look at the code sample given below:
public class Singleton
{
// Static object of the Singleton class.
private static volatile Singleton _instance = null;
/// <summary> /// The static method to provide global access to the singleton object. /// </summary> /// <returns>Singleton object of class Singleton.</returns>
public static Singleton Instance()
{
if (_instance == null)
{
lock (typeof(Singleton))
{
_instance = new Singleton();
}
}
return _instance;
}
/// <summary> /// The constructor is defined private in nature to restrict access. /// </summary>
private Singleton() { }
}
In the above code we have made the constructor as
private
, this will ensure that no one can create an object of this class using the new
keyword. Then we created a static volatile object of class Singleton. This object will serve as the single point of access to this class. Going ahead we have written a public static method GetInstance
(), this method is responsible for creating the static object of the Singleton class if it already doesn’t exist. If the object is already created, then this method will return an instance of the already created object. Hence the code will ensure creation of only one object of the Singleton class.In the above code the
lock
statement is used for thread safety. In multi-threaded environment we would require the creation of object in a thread safe manner. Furthermore the volatile
keyword is used to ensure that there is no optimizer reordering of the code.Look at the code given below. Is it an implementation of Singleton design pattern??? This I leave it to you… explore and enjoy understanding patterns…. :)
/// <summary>/// A sealed class providing access to it's ONLY readonly static instance./// </summary>sealed class SingletonCounter
{
public static readonly SingletonCounter Instance = new SingletonCounter();
private SingletonCounter() {}
}