C# | Singleton Design Pattern | Creational Design Pattern

Singleton pattern is one of the simplest design patterns in C#. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.

This pattern involves a single class which is responsible to create an object while making sure that only single object gets created. This class provides a way to access its only object which can be accessed directly without need to instantiate the object of the class.

- The Singleton pattern is a design pattern that restrict the instantiation he lifetime of the application, the instance remains same.

- Throughout the lifetime of the application the instance will remain same.

- Instance should be requested instead of created, if instance not available then create the instance, then provide otherwise provide available instance. 

Why we need Singleton design pattern?

- When there is single resource throughout the application. e.g- Database, Log File etc.

- When there is a single resource and there is very high chance for deadlock.

- When we want to pass instance from one class to another class.

Code Syntax -

public sealed class SingletonClass

{

    private static SingletonClass instance;

    private static object obj;

    private SingletonClass()

    {

    }

    private static SingletonClass GetInstance()

    {

        lock (obj)

        {

            if (instance == null)

            {

                instance = new SingletonClass();

            }

            return instance;

        }

    }

--------------------------------------------Program class--------------------------------------------------------  

  internal class Program

    {

        static void Main(string[] args)

        {

            SingletonClass objfetch = SingletonClass.GetInstance();

        }

    }

}

When to use it?

1.      Exactly one instance of a class is required.

2.      Controlled access to a single object is necessary.


Comments

Popular posts from this blog

C# | SOLID Principles

C# | Design Patterns