Singleton Pattern

The Singleton Pattern is a type of Creational Pattern of the Gang of Four Design Patterns. Before moving to the Singleton Design Pattern, let's first understand what a singleton is. A singleton is a class that allows only one object to be created. Hence, the Singleton Design Pattern is a pattern that restricts the instantiation of the class to one object only and provides a global point of access to it.

Characteristics of the Singleton Design Pattern

Implementation of Singleton Design Pattern

The following is the code for a thread-safe implementation of the Singleton Pattern:

  1. //sealed class
  2. public sealed class Singleton
  3. {
  4. //private, parameterless constructor
  5. private Singleton()
  6. {
  7. }
  8. //static variable that will hold the reference of the object created
  9. public static Singleton instance = null;
  10. //an object to make the implementation thread safe
  11. public static readonly object _lock = new object();
  12. //pubic static means of getting the reference of the object created
  13. public static Singleton GetInstance
  14. {
  15. get
  16. {
  17. //to make implementation thread-safe
  18. lock (_lock)
  19. {
  20. if (instance == null)
  21. {
  22. instance = new Singleton();
  23. }
  24. return instance;
  25. }
  26. }
  27. }
  28. }

In the code, the Singleton Design Pattern is thread-safe. Here the thread takes the lock on the shared object and checks whether or not the instance existed earlier or not, if the instance is null then only then is the instance created. This way it ensures that only one thread can create the instance.

Now in the main method we can fetch the instance of the singleton class using the public static reference as in the following:

  1. Singleton obj = Singleton.GetInstance;

Using this object we can make calls to any of the methods of the singleton class.

The following are the differences between a static class and a singleton class: