In the article we will discuss about singleton class in C#.NET.
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.
Example:
class SingletonClass
{
private static Singlet
|
public int tempVal
{
get; set;
}
//private constuctor
private
SingletonClass()
{
}
public static Singleto
nClass GetInstance()
{
if (obj == null)
{
obj = new Sing
letonClass();
}
return obj;
}
}
class SingletonClassProgra
m
{
public static void
Main(string[] args)
{
SingletonClass
obj1,obj2;
//obj1=new
SingletonClass(); //invlid due to constructore is
obj1=SingletonCla
ss.GetInstance();
obj1.tempVal =20;
obj2=SingletonClas
s.GetInstance();
Console.WriteLine(
" /********* singleton class Example **********/");
Console.WriteLine(
"variable value is {0}",obj2.tempVal); //value is 20
Console.Read();
}
}
Output:
- Singleton is a design pattern in software development.
- Singleton class is like a sealed class
0 Comments:
Post a Comment