Singleton

Design Pattern : Singleton

Tuba Mansoor
Latest posts by Tuba Mansoor (see all)

Design patterns provide solutions to recurring problems. Let’s have a look at one of the simplest design pattern – the Singleton design pattern. Sample code for this pattern can be found at Github.

Definition

This is a creational design pattern. In this pattern, only one instance of the class is created which has global access.

Advantages of the Singleton Design Pattern

Because the Singleton class encapsulates its sole instance, it can have strict control over how and when clients access it.

Disadvantages

  • The single responsibility principle states that one class should be responsible for only one thing. The singleton design pattern violates this because the class then becomes responsible for managing its life cycle.
  • Creates tight coupling, making the code tough to test.
See also  Leveraging OCEN Framework in Insurance

Difference between singleton & static class?

  • Singleton class instance can be passed as a parameter to methods, but static class instance cannot (as static class instances cannot be created).
  • Singleton can inherit other classes and implement interfaces, but static class cannot do so.

Implementation

namespace SingletonPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            Singleton.Instance.Print();
        }
    }

    public sealed class Singleton
    {
        private static Singleton instance = null;

        private Singleton()
        {
        }

        public static Singleton Instance {
            get {
                if (instance == null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }

        public void Print(){
            Console.WriteLine("Singleton instance called");
        }
    }
}

Features of the implementation

  • We have a private constructor for the singleton class, because of which it cannot be instantiated from outside the class.
  • The public static instance provides global access to the single created instance.

Further Reading

https://csharpindepth.com/articles/singleton