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