tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Design Patterns > Java Design Patterns > Pre Initialized Singleton

Pre Initialized Singleton 

This example shows creating a simple singleton. Singletons provides a mechanism to have a single instance of a class throughout the life cycle of the Application. It ensures a class has only one instance and provides a global point of access to it.

File Name  :  
com/bethecoder/tutorials/dp/singleton/pre/Singleton.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.dp.singleton.pre;

public class Singleton {

  /**
   * Pre-initialized singleton.
   */
  private static final Singleton instance = new Singleton();
  
  /**
   * Make sure to have private default constructor.
   * This avoids direct instantiation of class using 
   * new keyword/Class.newInstance() method
   */
  private Singleton() {
    init();
  }
  
  private void init() {
    //Initialization code 
  }
  
  public static Singleton getInstance() {
    return instance;
  }
}
   

File Name  :  
com/bethecoder/tutorials/dp/singleton/pre/Test.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.dp.singleton.pre;

public class Test {
  
  public static void main (String [] args) {
    
    System.out.println(Singleton.getInstance());
    System.out.println(Singleton.getInstance());
  }
}
   

It gives the following output. Check the object hash code, its identical for all calls to Singleton.getInstance() method.
com.bethecoder.tutorials.dp.singleton.pre.Singleton@250e250e
com.bethecoder.tutorials.dp.singleton.pre.Singleton@250e250e



 
  


  
bl  br