Introduction:
There is some cases when you want to have one and only one instance of a specific class and prevent anybody from having the ability to create more than one instance of that class. Singleton Design pattern came to solve this issue by defining a well known structure for your class
Example:
Singleton Design pattern can be used in Data repository or data collection where creation of more than one instance of this class can be resource wastage… Hence each client to singleton class is referencing to the same single shared object. Which will solve the issue.
public class Singleton { private static Singleton instance; private static int numOfReference; private static int numOfInstances = 0; private string code; private Singleton() { numOfReference = 0; numOfInstances++; code = “Code ” + numOfInstances.ToString(); } //Return instance of the Singleton class public static Singleton GetInstance() { if(instance == null) { instance = new Singleton(); } numOfReference++; return instance; } public static int ReferenceCounter { get { return numOfReference; } } public static int InstanceCounter { get { return numOfInstances; } } public string Code { get { return code; } set { code = value;} } } static void Main(string[] args) { Singleton instance1 = Singleton.GetInstance(); Console.WriteLine(“No. of references : ” + Singleton.ReferenceCounter); // should be 1 Console.WriteLine(“First Objects code: ” + instance1.Code); Console.WriteLine(“Instances Counter: ” + Singleton.InstanceCounter); // should be 1 Singleton instance2 = Singleton.GetInstance(); Console.WriteLine(“No. of references : ” + Singleton.ReferenceCounter); // should be 2 Console.WriteLine(“Second Objects code: ” + instance2.Code); Console.WriteLine(“Instances Counter: ” + Singleton.InstanceCounter); // should be 1 } |