Implementing Singleton Design Pattern using C#

Hello friends,

All of you must be aware of what Singleton Design Pattern is. Just to define it in one line, It is a pattern which allows creation of one and only instance of a class. 

The practical scenario where you can go with this pattern is having a print job class instance, single running instance of an application etc. 

The best example is Google Talk desktop application.
Let us try to implement this pattern via C# code.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPatternsDemo
{
    public class SingletonClass
    {
        private SingletonClass()
        {
        }

        //Implementation #1
        //static SingletonClass _instance = null;
        //public static SingletonClass GetInstance()
        //{
        //    if (_instance == null)
        //    {
        //        _instance = new SingletonClass();
        //    }
        //    return _instance;
        //}

        //Implementation #2
        //Be aware that in a multithreaded program, different threads could try
        //to instantiate a class simultaneously. For this reason, a Singleton
        //implementation that relies on an if statement to check whether the
        //instance is null will not be thread-safe. Do not use code like that!

        static readonly SingletonClass _instance = new SingletonClass();

        public static SingletonClass GetInstance
        {
            get
            {
                return _instance;
            }
        }

        public string GetWelcomeMessage()
        {
            return "Welcome to the Singleton world!! ";
        }
    }
}

The Singleton class above will be instantiated only once.
When the GetInstance is called, it will return the statically created instance of the class.

2 comments:

  1. Is this implementation Thread-safe?

    static SingletonClass _instance = null;
    static object lockThis;

    public static SingletonClass GetInstance()
    {
    lock(lockThis)
    {
    if (_instance == null)
    _instance = new SingletonClass();
    }

    return _instance;
    }

    ReplyDelete
  2. Yes that implementation is thread safe.

    ReplyDelete

Labels

.net .Net Instrumentation logging .net localization Agile amazon amazon elasticache amazon services AppDomain Application Domain architecture asp ASP.Net authentication authentication mechanisms Byte order mark c# cache canvas app cdata certifications class classic mode cloud cloud computing cluster code-behind Combobox compilation Configuration providers configurations connection connectionString constructors control controls contructor CSV CTS .net types conversion database DataGridView DataSource DataTable DataType DBML delegates design pattern dispose double encoding Entity framework Events exception handling expiry fault contracts fault exceptions function pointers functions generics help HostingEnvironmentException IIS inner join instance management integrated mode javascript join left outer join LINQ LINQ join LINQ to SQL memory leak methods microsoft model driven app modes in IIS MSIL multiple catch blocks no primary key Nullable Osmos Osmotic Osmotic communication Osmotic communications page events page life cycle partial class PMI powerapps preserve precision points private contructor ProcessExit Project management properties property protect connectionString providerName providers query regular expression repository Responsive Web Design return type run-time RWD Saas self join session session expiry sessions singelton singleton pattern software as a service source control system SQLMetal string toolstrip ToolStrip controls ToolStripControlHost tortoise SVN ToString() try catch finally update wcf web application web design web site web.config where-clause xml

Pages