Design Patterns - Singleton

In this article, I am explaining about the singleton design pattern and its common application areas. Singleton is one of the design patterns in the Gang of Four (GoF) design patterns.

Singleton is one of the design patterns from the Gang of Four (GoF) design patterns. It is a creational design pattern.
 
Singleton design pattern restricts the class to create multiple instances. This design pattern would ensure that the class should have only one instance alive at any given time.
 
To make a class a singleton, we can use the following steps.
  1. Create a class
  2. Create a private static member of type class
  3. Create a private constructor
In the above 3 steps, the 3rd step is an important one; i.e., if we create a class with a private constructor, then the outer class or the subclasses are not able to create objects of that class. Refer to the screenshot below.
  1.    public class Singleton  
  2.    {  
  3.         
  4.        private Singleton()  
  5.        {  
  6.            // private constructor  
  7.        }  
  8.    }  

  9.    class CallSingleton  
  10.    {  
  11.        public static void Main(string[] args)  
  12.        {  
  13.            Singleton instance = new Singleton();  
  14.          
  15.        }  
  16.    }  
The above highlighted statement will generate the 'inaccessible' error as below.
 
Design Patterns - Singleton
 
A sample implementation of the singleton design pattern is given below.
 
Singleton Class
  1.     public class Singleton  
  2.     {  
  3.         private static Singleton obj_singletonInstance=null// A static class instance  
  4.         private Singleton()  
  5.         {  
  6.             // private constructor  
  7.         }  
  8.         public static Singleton createInstace()  
  9.         {  
  10.             // static method : check whether the instace is null or not.   
  11.             // If null , it will create an instace and assign to obj_singletonInstance  
  12.             // and will return the value of the obj_singletonInstance  
  13.   
  14.             if (obj_singletonInstance==null)  
  15.             {  
  16.                 Console.WriteLine("Creating instance!");  
  17.                 obj_singletonInstance = new Singleton();  
  18.             }  
  19.             return obj_singletonInstance;  
  20.         }  
  21.         public void getMessage()  
  22.         {  
  23.             Console.WriteLine("This method is called using singleton instance!");   
  24.         }  
  25.   
  26.     }   
Main class
  1. class CallSingleton  
  2.    {  
  3.        public static void Main(string[] args)  
  4.        {  
  5.            Console.WriteLine("Design Patterns : Singleton \n ------------------");  
  6.   
  7.            Singleton instance; // object declared  
  8.            instance = Singleton.createInstace(); // initialized  
  9.            instance.getMessage();  
  10.   
  11.            Console.ReadKey();  
  12.          
  13.        }  
  14.    }  
Output
 
Design Patterns - Singleton

Where can we use the Singleton design pattern?

 
The use of the Singleton design pattern is based on the requirement. A few of the applicable areas of singleton design pattern are mentioned below.
 

Shared resource access

 
We can use the singleton design pattern to prevent concurrent access to a class. This design pattern can be used to make external resources usage limitation as required. For example, to prevent the multiple concurrent access to the shared printer in the network.
 

Cache

 
Another area where we can use a singleton design pattern is Cache. We can create Cache as a singleton object, so it can have a global point of reference and all future references by the client will be using it from the in-memory object.
 

Configuration Files

 
We can use this design pattern for accessing the configuration files. By using the singleton design pattern, we can create a single instance for the configuration file which can be accessed by multiple calls concurrently using the static config data loaded in the in-memory.
 

Logger

 
Singleton design pattern can be used for log file generation. Consider, if our application has a log generation utility and it will generate a log file based on the message, what will happen if the utility will be accessed by multiple clients concurrently?
 
They will create multiple instances and might make issues during concurrent access. We can create the logging utility class as a singleton class and make sure that no two clients could access it simultaneously.
 

Database Connection

 
We can use the singleton design pattern for the creation of the database connection instances. It will improve performance.
 
These are the only few common areas where we can use a singleton design pattern. We can find many more project-specific areas to use the singleton design pattern.