What is singleton?

Jak
Jak
Member
352 Points
151 Posts

Hi,

What is singleton?

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

Share:   fb twitter linkedin
Answers
Rahul Maurya
Rahul M...
Moderator
1170 Points
210 Posts
Marked as answer      

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
banner

Blog

Active User (2)

 Log In to Chat