C# Singleton Pattern
The Singleton design pattern's functionality is pretty much what you wouldexpect given its name, 'Singleton'. This pattern instantiates one instanceof the class once it is first called, and maintains that single instancethroughout the lifetime of the program. Once it is instantiated, all futurerequests will be through a single global point of access.
Below is a simple implementation of this pattern. I have added a publicvariable 'int x' into the code to make it obvious to the reader what isgoing on. The code apparently creates 2 instances of the class and assignesa value to x. Upon further investigation, it is clear that all updates to xare actually updating the same class. We update s1.x to 100. We then updates2.x to 200. We then output the value of s1.x thinking it will be 100, yetit is 200 since all updates and apparent instantiations of the class are allpointing to the same instance!
<%@ Page language="c#"%>
<script language="c#" runat=server>
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);
}




25. Aug, 2006 by 







No comments yet... Be the first to leave a reply!