Singleton Pattern
It restricts object of class to be created only once throught the application and provides global point of access to it. It also comes under creational
pattern like Factory pattern as it allows one of the best way to create object.
Steps
1) Define private static member of class type.
2) Define a private constructor.
3) Define public static method to provide global access to it.
Implementation of Singleton Pattern
public class SPattern
{
private static SPattern instance = null;
private SPattern()
{
}
public static SPattern GetInstance()
{
if(instance == null)
{
instance = new SPattern();
}
return instance;
}
}
class Program
{
static void Main(string[] args)
{
// SPattern s = new SPattern(); This is inaccessible due to protection level.
SPattern s1 =SPattern.GetInstance();
SPattern s2 = SPattern.GetInstance();
if (s1 == s2)
Console.WriteLine("Same objects");
else
Console.WriteLine("Different objects");
Console.ReadKey();
}
}
Here, We have private static instance of class SPattern. We have private constructor to prevent instantiation of class from outside (As you can see at Line 1 of Main method).
We have GetInstance() method to provide global access which will return same object all the time. When this piece of code will run s1 and s2 will have same instance and "Same objects" will
be printed.
Disadvantages of this implemention
It is not safe in multi- threaded environments as multiple thread can enter GetInstance() at same time and condition if(instance == null) can be true for multiple
threads and different instances of SPattern can be created which is voilation of Singleton Pattern.
What to Do Now ?
You may use approach called Static Intitialization to avoid this.
Static Initialization
public sealed class SPattern
{
private static readonly SPattern instance = new SPattern();
private SPattern(){}
public static SPattern GetInstance()
{
return instance;
}
}
Here, Object is only created when class is referenced for first time i.e during first call to GetInstance() method. Keyword readonly allows to create object either
during declaration or within in a constructor and private constructor prevents instantion from outside. In most cases static intialization is preferred.
0 Comment(s)