DotNet Mirror
  DNM facebook   DNM Google+   DNM Twitter   

Implementing Singleton class in .NET

By Ashok Nalam on 16 Dec 2012 | Category: C# | Tagged: class singleton design pattern 
In this article we will discuss about the implementation of singleton class in .NET with sample program.
  Discuss Add Comment   |  
Add rating Rate this resource   

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

  Discuss Add Comment    
Add rating Rate this resource   
About the Contributor
Member Since : 10 Dec 2012
Member Points (Level) : 9526  (Professional)
Location : INDIA
Home Page : http://dotnetmirror.com
About : I am admin of this site.
Rate this resource
 
Add your Comment
Name Email WebSite
Captcha Refresh


Comments (0)
No comments found, click here to add comment.
 
cheap jordans|wholesale air max|wholesale jordans|wholesale jewelry|wholesale jerseys