Follow by Email

Thursday, August 8, 2013

using singleton pattern in .net | example of using the singleton patter in .net c# | Design Patterns

Design Pattern : Singleton

Singleton pattern assures that only a single object will be created for any class and the same object will be used in the application.

Example (Adding Numbers ) :

Solution Explorer

Class file (here we will be writing the code for implementing singleton pattern)

public class CommonClass
    private static CommonClass _instance;
    protected CommonClass()
    public static CommonClass Instance()
        if (_instance == null) _instance = new CommonClass();
        return _instance;

    public int addNumber(int x, int y)
        return (x + y);



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ShowAddNumber.aspx.cs" Inherits="ShowAddNumber" %>

<!DOCTYPE html>

<html xmlns="">
<head runat="server">
    <form id="form1" runat="server">
        Enter Numbers to Add :<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br />
        <asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" />
        <br />

          Result 1: <asp:Label ID="Label1" runat="server" Text=""></asp:Label><br />
          Result 2: <asp:Label ID="Label2" runat="server" Text=""></asp:Label>

        <br />

        <asp:Label ID="lblMsg" runat="server" Text="Label"></asp:Label>


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ShowAddNumber : System.Web.UI.Page

    protected void Page_Load(object sender, EventArgs e)

    public void Button1_Click(object sender, EventArgs e)
        CommonClass s1 = CommonClass.Instance();
        Label1.Text = s1.addNumber(int.Parse(TextBox1.Text), int.Parse(TextBox2.Text)).ToString();

        CommonClass s2 = CommonClass.Instance();
        Label2.Text = s2.addNumber(int.Parse(TextBox1.Text) + 5, int.Parse(TextBox2.Text) + 5).ToString();

        if (s1 == s2)
            lblMsg.Text = "Same Object Used";


Output :