Singleton Pattern


Singleton Pattern:- A design pattern used in application when we need to restrict instantiation of a class to one object.

In following example, we have a Winform application. We need to maintain global variable. For it we create a singleton class and access it throughout application.

--------------Singleton Class------------


class
cGlobalVariable

{

    private string userName;

    private string passWord;

    private int patientID;

 

    private static cGlobalVariable objcGlobalVariable;

    private cGlobalVariable()

    {

    }

    public string UserName

    {

        get { return userName; }

        set { userName = value; }

    }

    public string Password

    {

        get { return passWord; }

        set { passWord = value; }

    }

    public int PatientID

    {

        get { return patientID; }

        set { patientID = value; }

    }

    public static cGlobalVariable GetInstance()

    {

        if (objcGlobalVariable == null)

        {

            objcGlobalVariable = new cGlobalVariable();

        }

        return objcGlobalVariable;

    }

 

}

-----------Use of Singleton class in Window form--------------

public partial class Form1 : Form

{

    public Form1()

    {

        InitializeComponent();

    }

 

    private void button1_Click(object sender, EventArgs e)

    {

        cGlobalVariable objcGlobalVariable = cGlobalVariable.GetInstance();

        label1.Text = objcGlobalVariable.UserName;

        objcGlobalVariable.PatientID = 572;

    }

 

    private void button2_Click(object sender, EventArgs e)

    {

        cGlobalVariable objcGlobalVariable = cGlobalVariable.GetInstance();

        label2.Text = objcGlobalVariable.PatientID.ToString();

    }

 

    private void Form1_Load(object sender, EventArgs e)

    {

        cGlobalVariable objcGlobalVariable = cGlobalVariable.GetInstance();

        objcGlobalVariable.UserName = "Amit Dhania";

    }

}

Above code give simple way to use singleton pattern in application where we can keep static variable values available throughout application.


Similar Articles