Introduction

In Singleton Design Pattern one class has only single instance of a class, and provide a global point of access to it.

No client can create an instance of the object from outside.

In a singleton class

1. Constructor is defined as private.

2. Method and instance as static.

Code Example

Create a C# Project name [Singleton] in Visual Studio 2010 and add a class named “Singleton” as below.

 

//Singleton.cs

 using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows.Forms;

 

namespace SingleTon

{

   public  class Singleton

{

 

   private static Singleton singleton;

   private Singleton() {} // private constructor

   public static Singleton CreateInstance() //Static Method

   {

      if (singleton == null)

      {

         singleton = new Singleton(); 

 

        

      }

      return singleton;

   }

}

}

 

In “Form1” of the project, write below code in form load event.

private void Form1_Load(object sender, EventArgs e)

        {

            Singleton ObjA = Singleton.CreateInstance();

            MessageBox.Show("SingletonClass Instance Created");

            Singleton ObjB = Singleton.CreateInstance();

          

            if (ObjA == ObjB)

            {

              

                MessageBox.Show("ObjA and ObjB Now having Same reference");

            }

        }

When to use Singleton

A singleton should be used when managing access to a resource which is shared by the whole application and it would be destructive to potentially have multiple instances of the same class.

Can be used while logging and connection pooling etc. in real time application.