Singleton Pattern
The purpose of the Singleton pattern is to make sure that there is only one instance of a class and that there is a global access point to that object.
The pattern ensures that the class is instantiated only once and that all requests are directed to that one and only object.
The class needs to make the following modifications in order to implement the Singleton Pattern
- The constructor needs to be made private and add a private static constructor as well.
- A private static read-only object is required, that is internally instantiated using the private constructor.
- A public static property is required, that accesses the private object.
It is the public property that is now visible to the caller.
All constructor requests for the class go to the property. The property accesses the private static object and
will instantiate it if it does not already exist.
{
private SingletonDemo()
{
}
private static SingletonDemo _myobject = new SingletonDemo();
public static SingletonDemo isInstatiated
{
get { return _myobject; }
}
}
As soon as the class is instatiated, isInstatiated property is set be calling its private constructor.
Let’s call it to see how it works
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("Simple Singleeton Demo");
Response.Write("");
if (SingletonDemo.isInstatiated != null)
{
Response.Write("Object initialized");
}
}
To further extend the demo, try to instatiate two objects for this class and see if they point to different references.
Although I assure you that it always creates just one instance, please try it yourself to believe if I’m correct.
Hope this was helpful,
Till next time we connect…Happy Coding!!!
Comments
Post a Comment