Saturday, September 18, 2010

Singleton Class

A Class that can be instantiated only once is called Singleton Class. i.e We can create only one object for a Singleton class.

Constructor in a Singleton Class has to be made private so that object cannot be created outside the class.

public Class SingleTonDemo
{
private SingleTonDemo // Note that Constructor is made Private.
{
}
public Static SingleTonDemo Obj;
public int a;
//create a property which gives the only created object..
public Static SingleTonDemo GetOnlyObject
{
if(Obj==null)
{
Obj = new SingleTonDemo();
return Obj;
}
}
} //end of the class

SingleTonDemo Ref1;
SingleTonDemo Ref2;

Ref1=SingleTonDemo.GetOnlyObject;
Ref2=SingleTonDemo.GetOnlyObject;

Ref1.a=10;

Console.Writeline(Ref2.a);

//Output 10...since the both Ref1 and Ref2 referencing to the same object.


http://msdn.microsoft.com/en-us/library/ff650316.aspx

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.