Dec 15, 2014

Singleton design pattern in C#



The objective of the Singleton pattern is to ensure a class has only one instance, and provide a global point of access to it.
In 10th standard you will read have a mathematical concept of algebra unit set (For example, the set {0} is a singleton, it has only on element) this is called singleton also. Like unit set, singleton pattern restrict the instantiation of a class to one object. This is useful when one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists.
The advantages of a Singleton Pattern are:
1.       Singleton pattern can be implemented interfaces.
2.       Singleton pattern can be also inherited from other classes.
3.       Singleton pattern can be lazy loaded.
4.       Singleton pattern can be extended into a factory pattern.

See below sample:
/// <summary>
/// Thread-safe singleton example created at first call
/// </summary>
public sealed class Singleton
{
    private static readonly Singleton _instance = new Singleton();
    private Singleton() { }
    public static Singleton Instance
    {
        get
        {
            return _instance;
        }
    }
}
Note: use singleton when 

  • Exactly one instance of a class is required.
  • Controlled access to a single object is necessary.