Singleton Design Pattern with C#

Design Pattern

Design pattern is a solution of known problems. These are strategies of solving commonly occurring problems. A design pattern is not a finish design. It is like a template to solve a problem.

Singleton Design Pattern

Singleton is a software design pattern. It is restrict to create object more than once. This is actually needed when one object can perform its action in whole system. We frequently use a database connection object to connect with database. We don’t need multiple objects to create connection with database and close it. We can use singleton in this scenario.

Implementation of Singleton by C#

Step 1: Create EmployeeInfo class

This class is to hold employee information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Singleton
{
public class EmployeeInfo
{
public string EmpName { get; set; }
public string EmpDesignation { get; set; }
public int MonthlySalary { get; set; }
}
}

Step 2: Create a singleton class

Here EmployeeService is a singleton class. Constructor of this class is private so that nobody can create its instance from outside.  Instance() is a static method which creates instance of the singleton class. It actually forces that only one instance of the object will be created. Lock() is used to create instance of the singleton pattern in thread safe manner in multi threaded environment. The other two methods are used to add employee information in list and get employee salary. These two are as usual method.Don’t mix up Singleton class and Static class. Keep in mind; in static class everything must be static like Method, constructor, properties. But in singleton class it is not required. Hope, you will be clear after the following example.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Singleton
{
///
/// EmployeeService is a singleton class
///

public class EmployeeService
{

//Static object of singleton class
private static EmployeeService instance;

private List lstEmployeeInfo = null;

///
/// Restrict to create object of Singleton class
///

private EmployeeService()
{
if (lstEmployeeInfo == null)
{
lstEmployeeInfo = new List();
}
}

///
/// The static method to provide global access to the singleton object.
///

/// Singleton object of EmployeeService class
public static EmployeeService Instance()
{

if (instance == null)
{
//Thread safe singleton

lock (typeof(EmployeeService))
{
instance = new EmployeeService();
}
}

return instance;
}

///
/// Add employee information to the Employee information list
///

///

public void AddEmployeeInfo(EmployeeInfo objEmployeeInfo)
{
lstEmployeeInfo.Add(objEmployeeInfo);
}

///
/// Get Salary by Name
///

////// Salary of Employee

public int GetEmployeeSalaryByName(string name)
{
int monthlySalary = 0;
foreach (EmployeeInfo objEmployeeInfo in lstEmployeeInfo)
{
if (objEmployeeInfo.EmpName.Contains(name))
monthlySalary = objEmployeeInfo.MonthlySalary;
}
return monthlySalary;
}

}
}

Step 3: Access singleton class

This class creates an instance of singleton class by EmployeeService objEmployeeService = EmployeeService.Instance(); and access singleton class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Singleton
{
class Program
{
static void Main(string[] args)
{
EmployeeInfo objEmpInfo1 = new EmployeeInfo() { EmpName = "Mahedee", EmpDesignation = "Senior Software Engineer", MonthlySalary = 00000 };
EmployeeInfo objEmpInfo2 = new EmployeeInfo() { EmpName = "Kamal", EmpDesignation = "Software Engineer", MonthlySalary = 30000 };

//Create a singleton object
EmployeeService objEmployeeService = EmployeeService.Instance();

objEmployeeService.AddEmployeeInfo(objEmpInfo1);
objEmployeeService.AddEmployeeInfo(objEmpInfo2);

Console.WriteLine(objEmpInfo2.EmpName + " : " + objEmployeeService.GetEmployeeSalaryByName("Kamal"));

Console.ReadLine();

}
}
}
Please share, if it is helpfulShare on FacebookShare on LinkedInTweet about this on TwitterShare on Google+Email this to someonePrint this page

5 thoughts on “Singleton Design Pattern with C#

  1. Your singleton is implemented incorrectly for threaded environments. If you are in a threaded environment please do not use the above code as a reference.

    Please go back and re-read here (http://msdn.microsoft.com/en-us/library/ff650316.aspx). Also, many consider the use of a singleton evil.
    (1) tightly coupled, (2) testing (3) poor design (4) object lifecycle ….

    In fact, depending of the types of hardware (in a threaded environment, master/slave and flushing of cache) you may not implement the correct behavior.

    On a side note, remember the rule — use generics when the the behavior of the class does not change based on the type (i.e. Stack, Queue, even a Singleton if you are so inclined [but the semantics of the type may constrain this)

    Finally, there is the notion of connection pooling you made reference to — please see this article (http://msdn.microsoft.com/en-us/library/vstudio/8xx3tyca(v=vs.100).aspx) …

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>