Ad (728x90)

Filled Under:

What is Singleton pattern?

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.

Unknown

Author & Editor

Has laoreet percipitur ad. Vide interesset in mei, no his legimus verterem. Et nostrum imperdiet appellantur usu, mnesarchum referrentur id vim.

0 comments:

Post a Comment

Please write to us here...

 

We are featured contributor on entrepreneurship for many trusted business sites:

  • Copyright © Tekhnologia™ is a registered trademark.
    Designed by Templateism. Hosted on Blogger Templates.