CodeSnip: Working with Singleton Design Pattern using C#
page 1 of 1
Published: 29 Mar 2006
Unedited - Community Contributed
Abstract
The singleton pattern is one of the best-known patterns in software engineering. Often, this pattern is used to represent parts of the system that there can only be one of, like the MSN messenger or Yahoo messenger can be instantiated, or run, only once at a time for a given account. In this code snippet, Vishal will demonstrate the Singleton Design Pattern using C#.
by Vishal Patil
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 9461/ 58

Overview

The singleton design pattern is focused on having one—and only one—instance of an object. It instills encapsulated control of the object from a common place. Most commonly, singletons don't allow any parameters to be specified when creating the instance - as otherwise a second request for an instance but with a different parameter could be problematic! The class implemented using this pattern is responsible for keeping track of its sole instance rather than relying on global variables to single instances of objects.

This article deals only with the situation where no parameters are required. The following sample application depicts how to implement the singleton design pattern in Windows Application using C#.

Software Requirements

Microsoft Visual C# 2005 Express Edition (or better)

Create the Child form

Add a new Windows Application project (with name as SingletonDesignPattern) and to it add a form as frmchild and paste the following code in it as shown below:

Listing 1

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
 
namespace SingletonDesignPattern
{
  public partial class frmChild: Form
  {
    private static int iCount = 0;
 
    public frmChild()
    {
      InitializeComponent();
      iCount = iCount + 1;
    }
 
    public static int Count
    {
      get
      {
        return iCount;
      }
    }
  }
}

In listing 1, firstly a static variable iCount is declared which keeps the count of the number of instances of the child form. Then in the form constructor, the iCount variable is incremented every time an instance of the form is created.

 

Next, through the Count Public property, the count of the number of instances of the form is returned to the calling form.

Finally, in the frmChild_FormClosing event, the iCount variable is set to zero when the frmchild dialog is closed. This is done to allow the user to open the frmchild dialog again from the Main form if the frmchild dialog is not open.

Create the Parent form

Add one more form called frmParent to the above windows application project. To this form, add a Menustrip control with the name menuToolStripMenuItem. Add a menuitem with name of ChildForm to the Menustrip control. The screen should look as below:

Figure 1

Paste the following code in the click event of the ChildForm MenuItem.

Listing 2

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
 
namespace SingletonDesignPattern
{
  public partial class frmParent: Form
  {
    public frmParent()
    {
      InitializeComponent();
    }
 
    private void childFormToolStripMenuItem_Click(objectsender, EventArgs e)
    {
      frmChild objform = new frmChild();
 
      if (frmChild.Count == 1)
        objform.Show();
    }
  }
}

In Listing 2, first an instance of frmChild is created and then it is checked whether this is the first instance of frmChild.  If yes, it displays the frmChild dialog. If there is already an instance of thefrmchild dialog open, other instances of frmChild dialog will not be opened.

Now run the Main form and click the childform menuitem upon which frmChild dialog is displayed as shown below.

Figure 2

 

Again click the childform menuitem many times, but this time additional instances of the frmChild dialog will be not opened. Notice that at any one time, we are able to open Childform dialog only once from the Main form.

Downloads

[Download Sample]

Conclusion

The Singleton design pattern has proven to be a useful pattern in many programs. Now, the code in this code snippet shows how to implement that same pattern in a .NET Windows Application. There are various different ways of implementing the singleton pattern in C#.

 

Resources

Session Based Singleton

Singleton Design Pattern at dofactory.com



User Comments

Title: Can we please remove this article as it is INCORRECT!   
Name: Consultant
Date: 2010-09-15 5:26:34 AM
Comment:
All readers of this article, please be warned that this is an INCORRECT implementation of the Singleton. As a matter of fact, it is NOT EVEN SINGLETON as he creates objects every single time.

Could the SiteAdmins please remove this article. Thank you.
Title: Wrong Implementation   
Name: Nitin Mittal
Date: 2007-06-19 3:36:48 PM
Comment:
This is wrong demonstration to show singleton concept..in fact its not singleton pattern...
Title: Re: Set it back to null   
Name: RL
Date: 2007-02-22 8:29:33 PM
Comment:
Absolutely agree with Az here. Not a correct implementation of the singleton pattern.

Further to bm's comment, instead of setting the instance=null in the FormClosing event handler you can set it in the Dispose method. When the Form is closed its components get disposed hence the instance also can be set to null here. This will also make sure that you don't get ObjectDisposedException.
Title: set it back to null   
Name: bm
Date: 2006-07-24 5:52:41 AM
Comment:
I'd like to contribute to what Az showed here.
I'm working with MDI forms - i want to open an instance of a singleton form, then close it, and then open it again and so on..
In such a situation, if we don't want to get "ObjectDisposedException", we should set the static field to NULL every time the singleton form is closed.
as in Az's example:

private void _windowClosedEventHandler(object sender, EventArgs e) { _childInstance = null; }

plz correct me if i am wrong or it could be done better way;)

and then of course raise an appropriate event 'FormClosed' on closing a frmChild form.
Title: Misleading article !!   
Name: Anwar
Date: 2006-06-14 7:06:27 AM
Comment:
I think, Az is absolutely right and this article is misleading the readers. Please correct it.
Title: RE: Try this   
Name: Lorad
Date: 2006-05-11 10:11:37 AM
Comment:
Ajai, that just ensures you can never get the object again. That is not really the singleton patern either, while it is useful to ensure you can never create the form again, it does not implement the singleton patern.
Title: Or this one   
Name: Ajai NP
Date: 2006-05-02 5:29:06 AM
Comment:
public partial class frmChild: Form
{
private static int iCount = 0;
private frmChild()
{
InitializeComponent();
}
public static frmChild CreateObject()
{
return ++iCount>1?null:new frmChild();
}
}
Title: +1 for not OOP   
Name: Lorad
Date: 2006-04-11 12:21:49 PM
Comment:
Az is right this is not OOP and is something that should be removed from the site, if someone used this as a sinlgeton patern example in an interview I would turn them away.

Here is another possible way....

public partial class frmChild : Form
{
private static frmChild instance = null;
private frmChild() { InitializeComponent(); }

static frmChild() { instance = new frmChild(); }
public static frmChild Get() { return instance; }
}

C# supports static constructors that are executed one time and can be used to initialize any static members. It won't be called until the first instance of the object is used.

Az's way is the normal way you think of this, but thougt I would throw this out for learning purposes.
Title: Not an OOP   
Name: Az
Date: 2006-04-07 3:36:53 PM
Comment:
This is an incorrect implemention of Singleton pattern. What you are doing is essentially creating as many instances of child forms as requested (using up memory every time and overburdening the GC to collect it) but as a smoke screen, do the count check and display the first created form - what an incorrect form of OOProgramming. Pure implementation of Singleton should rest on the object taking care of just one instance of it exists and the burden should not be on the client using it.

The solution: Make the constructor private and using a static member that instantiates an instance of this object. Here is an example.

public partial class frmChild: Form
{
private static frmChild _childInstance = null;

private frmChild()
{
InitializeComponent();
}

public static frmChild GetChild()
{
if (_childInstance == null)
_childInstance = new frmChild();

return _childInstance;
}
}
}

from the client side code, all you need to do is...

frmChild objChild = frmChild.GetChild();

-- add the necessary exception handlers. Hope this was helpful. Please let me know if you have additional questions.






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-03-28 12:42:43 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search