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