The Singleton class can be used in various places where one would need a common repository of information that can be accessed from all objects in an application
GOF defined the Singleton Pattern as follows
SingleTon Class Implementation“Ensure a class has only one instance, and provide a global point of access to it.”
public class Singleton
{
private static Singleton _singleton = null;
private static DateTime _createdtime;
private Singleton() {}
public static Singleton Instance
{
get
{
if (_singleton == null)
{
_singleton = new Singleton();
_createdtime = DateTime.Now;
}
return _singleton;
}
}
public String ShowObjectCreation()
{
return _createdtime.ToString();
}
}
Create an aspx page ,add the below in the page load
void Page_Load(object sender, EventArgs e)
{
Response.Write("
1) Time :" + Singleton.Instance.ShowObjectCreation());
1) Time :" + Singleton.Instance.ShowObjectCreation());
Response.Write("
2) Time :" + Singleton.Instance.ShowObjectCreation());
2) Time :" + Singleton.Instance.ShowObjectCreation());
}