Singleton Pattern
This is a very popular creational pattern which restricts a class to have only one instance.
Example: "Prime Minister of India" is a singleton pattern as he/she has unique responsibilities and attributes.
Implementation: A singleton class can't have a public constructor and it has to be sealed. The entry point to get the singleton instance would be a static method or a static property.
public sealed class PrimeMinister
{
private static PrimeMinister instance = new PrimeMinister();
private PrimeMinister(){ }
public static PrimeMinister Instance
{
get { return instance; }
}
}
Thread safe
public sealed class Singletone
{
private static Singletone instance=null;
//constructor
private Singletone(){ }
Object objlock=new Object();
public static Singletone Instance
{
get {
if(instance==null)
{
Lock(objlock)
}
return instance;
}
}
}
This is a very popular creational pattern which restricts a class to have only one instance.
Example: "Prime Minister of India" is a singleton pattern as he/she has unique responsibilities and attributes.
Implementation: A singleton class can't have a public constructor and it has to be sealed. The entry point to get the singleton instance would be a static method or a static property.
public sealed class PrimeMinister
{
private static PrimeMinister instance = new PrimeMinister();
private PrimeMinister(){ }
public static PrimeMinister Instance
{
get { return instance; }
}
}
Thread safe
public sealed class Singletone
{
private static Singletone instance=null;
//constructor
private Singletone(){ }
Object objlock=new Object();
public static Singletone Instance
{
get {
if(instance==null)
{
Lock(objlock)
{
if(instance==null)
{
Instance=NEW
Singletone();
}
}
}
return instance;
}
}
}
0 comments:
Post a Comment