Definition:
“A class which can be instantiated only once is called singleton class”.
The term singleton is derived from the mathematics concept of a singleton. Singleton is set with only one element. E.g.: Set {0} is a singleton.
How to achieve singleton class?
- Mark the constructor as private so that outside the class it’s not possible to create instance of the class.
- Create static/Shared method can be added to the class to create instance of the class and return the reference of the object.
Sample Program:
class SingletonClass
{
private static SingletonClass obj;
public int tempVal
{
get; set;
}
//private constuctor
private SingletonClass()
{
}
public static SingletonClass GetInstance()
{
if (obj == null)
{
obj = new SingletonClass();
}
return obj;
}
}
class SingletonClassProgram
{
public static void Main(string[] args)
{
SingletonClass obj1,obj2;
//obj1=new SingletonClass(); //invlid due to constructore is private. Error as inaccissible due to protection level
obj1=SingletonClass.GetInstance();
obj1.tempVal =20;
obj2=SingletonClass.GetInstance();
Console.WriteLine(" /********* singleton class Example **********/");
Console.WriteLine("variable value is {0}",obj2.tempVal); //value is 20 because both obj1,obj2 are referring to same object
Console.Read();
}
}
Output:
Data Points
- Singleton is a design pattern in software development.
- Single class is like a sealed class