Skip to content

dotnet-simformsolutions/singleton-design-pattern

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Singleton Design Pattern

  • The Singleton pattern is a design pattern that restricts the instantiation of a class to one object and provides a way to access its object. This is useful when exactly one object is needed to coordinate actions across the system. That means we need to use the Singleton Design Pattern in C# to ensure that only one instance of a particular class will be created and provide simple global access to that instance for the entire application.

    image

  • As you can see in the above diagram, different clients (Client A, Client B, and Client C) are trying to get the singleton instance. Once the client gets the singleton instance, they can invoke the methods (Method 1, Method 2, and Method n) using the same instance.

Implementation Guidelines of Singleton Design Pattern in C#:

  • We need to declare a constructor that should be private and parameterless. This is required because it will restrict the class from being instantiated from outside the class. It only instantiates from within the class.
  • The class should be declared sealed, ensuring it cannot be inherited. This is going to be useful when you are dealing with the nested class.
  • We must create a private static variable referencing the class’s singleton instance.
  • We also need to create a public static property/method that will return the singleton instance of the class. This method or property first checks whether an instance of the singleton class is created. If the singleton instance is created, it returns that instance; otherwise, it will create an instance and then return it.

Example of Singleton Design Pattern using C#

  • No Thread-Safe Singleton Design Pattern Implementation in C#

    • Singleton class without thread safe

      image

      image

      image

      As you can see if we run in parallel environment or in muthithreading environment then it will create multiple object of singleton class so above singleton class is not thread safe.

  • Thread-Safe Singleton Design Pattern Implementation in C#

    • Singleton class with thread safe

      image

      image

      image

      As you can see if we run in parallel environment or in muthithreading environment then it will create not multiple object of singleton class so above singleton class ss now thread safe.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •  

Languages