What is Singleton pattern?

Description or Definition: A class need to create single instance through out Application, is used to encapsulate the creation of an object in order to maintain control over it. This not only ensures that only one is created, but also allows lazy instantiation; that is, the instantiation of the object can be delayed until it is actually needed. For example, Logger class, which should follow Singleton pattern.

This code demonstrates how the Singleton pattern can be used to create a counter to
provide unique sequential numbers, such as might be required for use as primary keys in a
database:

File Name: Logger.java

public class Logger {
  private static Logger instance;
  private static int counter;
  private Logger()
  {
     counter = 0;

   }
   public static synchronized Logger getInstance()
   {
      if(instance==null) // Lazy instantiation
     {
         instance = new Logger();
      }
     return instance;
    }
    public static synchronized int getNext()
   {
        return ++counter;
    }
  }

Please find below the things required to take care about this implementation, These restrict the user to make another instance of class for an application:

  1. Method is Synchronized to ensure that class is thread-safe.
  2. This class can’t be sub-classed because the constructor is private.