How to use Singleton pattern


Main theme of Singleton Pattern is there will be only one instance of a class. In the below example there is no way to create multiple instance of the class SingletonPatternTest

public class SingletonPatternTest
{
static SingletonPatternTest oSingletonPatternTest;

public int Count
{
get;
set;
}

private SingletonPatternTest()
{

}

public static SingletonPatternTest GetInstance()
{
if (oSingletonPatternTest == null)
{
oSingletonPatternTest = new SingletonPatternTest();
}

return oSingletonPatternTest;
}
}

 SingletonPatternTest oSingletonPatternTest  = SingletonPatternTest.GetInstance(); /*This always returns the same instance*/

oSingletonPatternTest.Count=10;

 SingletonPatternTest oSingletonPatternTestNew  = SingletonPatternTest.GetInstance();

Response.Write(“Count”+oSingletonPatternTestNew.Count.ToString()); /*This will write count value as 10*/