What is singleton?

Jak
Jak
908 Points
132 Posts

Hi,

What is singleton?

Views: 9563
Total Answered: 1
Total Marked As Answer: 1
Posted On: 25-Aug-2015 22:44

Share:   fb twitter linkedin
Answers
Rahul Maurya
Rahul M...
4916 Points
27 Posts
         

Hi Jak,

Singleton is a design pattern. It is used when you need only one instance of a class in your application.

We can use static for creating singleton pattern as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication2
{
 
//Eager intialization of singleton pattern
 
public class Singleton
private static Singleton Instance = new Singleton(); 
private Singleton() { }
 
public static Singleton GetInstance {
get
{
 
return Instance;
}
}
}
 
}

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication2
{
 
//Lazy intialization of singleton pattern
 
public class Singleton
private static Singleton Instance = null; 
private Singleton() { }
 
public static Singleton GetInstance {
get
{
if(Instance == null){
Instance =new Singleton();
}
return Instance;
}
}
}
 
}

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication2
{
 
//Thread safe intialization of singleton pattern
 
public class Singleton
private static Singleton Instance = null; 
private Singleton() { }
private static object lockThis = new object();
public static Singleton GetInstance {
get
if (lockThis){
if (Instance == null)
Instance =new Singleton();
}
return Instance;
}
 
}
}
 
}
Posted On: 26-Aug-2015 22:19
 Log In to Chat