Singleton

singleton design pattern

Singleton Design Pattern:

Singleton design pattern is a creational design pattern in software engineering which restricts the instantiation of class object to a single instance. When exactly one class object is required across the system, we use singleton design pattern which restricts from creating additional objects of the same class.

Singleton design pattern is one of the Gang of Four design patterns. It solves problems like:

  • How to ensure the creation of a single instance of a class?
  • How to make this instance accessible across the system?
  • How a class can control its instantiation?
  • How to restrict the number of instances to one?
  • How to hide constructor of a class?

It is simplest design pattern with only few lines of code. Remember it should not be confused with global variables, objects or instances. We use Singleton design pattern when we need exactly one instance, not less than 1 and not more than 1. However, we can use them in place of final global variables that are not required to be replaced.

Singleton Design Pattern UML Diagram

singleton design pattern

Example Scenarios to use Singleton Design Pattern

If we consider an example of database connection scenario, where a website connects to the database to fetch data. We know that an object creation allocates memory for storing instance’s information. We will prefer to save our system’s resources in terms of memory by creating a single instance of database class for connections and executing queries.

Other examples may include situations where:

  • Abstract Factory design pattern is used.
  • Builder design pattern is used.
  • Prototype design pattern is used.
  • Facade design pattern is used where only Facade object is required.
  • State design pattern is used.

Remember, singleton design pattern is not always applicable all the times in the mentioned scenarios. You will have to check feasibility of your scenario. It should not be used when passing an object as a reference to objects is easy than making it accessible globally.

If you have past experience in Java programming language, you might have used java.lang.Runtime and java.awt.Desktop.

java.lang.Runtime provides Runtime class which is singleton and allows application to interface with environment in which application is running. getRuntime() method can be used to obtain current runtime. Hence, it is single class.

java.awt.Desktop provides Desktop class which allows application to launch associated applications registered on native desktop to handle file or URI. For example, launching default browser, sending or viewing email via default email client, opening default text editor to open, edit or print file. Desktop class can not be instantiated from application. Hence, it is also an example of Singleton class.

Intent of Singleton Design Pattern

  • Creation of a single instance
  • Global access to the instance
  • Hiding of class constructor

Steps to Remember for Singleton Design Pattern

  • Define a static object of private access modifier in single instance class.
  • Define a static accessor method with public access modifier in single instance class.
  • Create an object in the accessor function.
  • Define all constructors to be private or protected.
  • The created instance can be accessed via the accessor method.

Applications of Singleton Design Pattern

Cache

If we are implementing a class to store cache, we can apply Singleton design pattern to create object which will have a global reference for all future calls to cache object the client application will use in-memory object.

Logger

Singleton design pattern can be used by Logger Utility class to edit log files. Thus avoiding multiple users access to log file at the same time.

Hardware Interface Access

If external hardware resource usage limitation is required, singleton classes can be used to prevent concurrent access of class. For example, printer spooler can be sent multiple jobs by different users at a time. To avoid concurrent access resulting in deadlock, Singleton design pattern can be applied here.

Configuration File

A configuration file can be accessed via Singleton object. Because in an application, configuration file remain same, hence there is no need to instantiate an object for each user. A single created singleton object can be used by all users. If it is not already created, on request from client, an object will be created. If object is already created then on request from client, the object will be reused.

Implementation of Singleton Design Pattern

Singleton design pattern can be implemented in various ways using different programming languages. We will not cover all programming language implementations. One kind of implementation is given below.

Singleton Design Pattern in Java

The following example has been implemented in Java Programming language.

//SingletonClass.java
public class SingletonClass {

   //create an object of SingletonClass
   private static SingletonClass instance = new SingletonClass();

   //make the constructor private so that this class cannot be
   //instantiated
   private SingletonClass(){}

   //Get the only object available
   public static SingletonClass getInstance(){
      return instance;
   }

   public void showMessage(){
      System.out.println("Hello Singleton!");
   }
}
//SingletonTest.java

public class SingletonTest {
   public static void main(String[] args) {

      //illegal construct
      //Compile Time Error: The constructor SingletonTest() is not visible
      //SingletonTest object = new SingletonTest();

      //Get the only object available
      SingletonTest obj = SingletonTest.getInstance();

      //show the message
      obj.showMessage();
   }
}
Output
Hello Singleton!

Leave a Reply

Your email address will not be published. Required fields are marked *