Hello
Please send me the details of the what is SINGLETURN in dotnet.
My email id is
Hello
Please send me the details of the what is SINGLETURN in dotnet.
My email id is
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Niradhip ChakrabortyPosted Apr 25, 2008, 3:50 PM
Are you looking for Singleton Pattern!!!!!
The Singleton design pattern's functionality is pretty much what you would expect given its name, 'Singleton'. This pattern instantiates one instance of the class once it is first called, and maintains that single instance throughout the lifetime of the program. Once it is instantiated, all future requests will be through a single global point of access.
Below is a simple implementation of this pattern. I have added a public variable 'int x' into the code to make it obvious to the reader what is going on. The code apparently creates 2 instances of the class and assignes a value to x. Upon further investigation, it is clear that all updates to x are actually updating the same class. We update s1.x to 100. We then update s2.x to 200. We then output the value of s1.x thinking it will be 100, yet it is 200 since all updates and apparent instantiations of the class are all pointing to the same instance!
<%@ Page language="c#"%>
class Singleton
{
// Variable
public int x= 0;
// Fields
private static Singleton instance;
// Empty Constructor
protected Singleton() {}
// Methods
public static Singleton Instance()
{
// Uses "Lazy initialization"
if( instance == null )
instance = new Singleton();
return instance;
}
}
private void Page_Load(object sender, System.EventArgs e)
{
// 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" );
s1.x= 100;
Response.Write("
s1.x=" + s1.x);
s2.x= 200;
Response.Write("
s2.x=" + s2.x);
// Updates to x are updating same instance
Response.Write("
s1.x=" + s1.x);
}