Search Forum
(57415 Postings)
Search Site/Articles

Archived Articles
712 Articles

C# Books
C# Consultants
What Is C#?
Download Compiler
Code Archive
Archived Articles
Advertise
Contribute
C# Jobs
Beginners Tutorial
C# Contractors
C# Consulting
Links
C# Manual
Contact Us
Legal

GoDiagram for .NET from Northwoods Software www.nwoods.com


              
Printable Version

Singleton Pattern
By Dev Team

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#"%>
<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); } Singleton