What is Singleton Pattern
Would like to know what is Signleton pattern. Where it is used and why we use it.
1 Answer
Know the answer? Post it. Somebody with the same question will find it here.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Tejaswini Prashant J78 reputationPosted May 19, 2009, 12:12 AM EDT
As the instance we are using thru out the appln, that is lways static.
Chk this code
// Fields
private static Singleton instance;
// Empty Constructor
protected Singleton() {}
// Methods
public static Singleton Instance()
{
if( instance == null )
instance = new Singleton();
return instance;
}
}
protected void Page_Load(object sender, EventArgs e)
{
// here we are creating the instance using singleton class
// Constructor is protected
// Prevented from using 'new' keyword
Singleton s1 = Singleton.Instance();
Singleton s2 = Singleton.Instance();
if( s1 == s2 )
Response.Write( "s1 & s2 are the same instance" );
// how we can use the class variables
s1.x= 100;
Response.Write("<br>s1.x=" + s1.x);
s2.x= 200;
Response.Write("<br>s2.x=" + s2.x);
// Updates to x are updating same instance
Response.Write("<br>s1.x=" + s1.x);
}
Hope this will help u :)