Author: techfox9

Design Patterns – Singleton pattern (Creational) basic example..

Saturday, July 12th, 2008 @ 1:55 pm

Pattern used to manage resources when a single instance of one is required
to coordinate actions across an application.

From http://en.wikipedia.org/wiki/Singleton_pattern

The simplest way:

public class Singleton {
   private static final Singleton INSTANCE = new Singleton();
 
   // Private constructor prevents instantiation from other classes
   private Singleton() {}
 
   public static Singleton getInstance() {
      return INSTANCE;
   }
 }

The ‘lazy loading’ way.. by Bill Pugh (static code analysis with FindBugs and more..)

public class Singleton {
   // Private constructor prevents instantiation from other classes
   private Singleton() {}
 
   /**
    * SingletonHolder is loaded on the first execution of Singleton.getInstance() 
    * or the first access to SingletonHolder.INSTANCE, not before. (lazy!)
    */
   private static class SingletonHolder { 
     private static final Singleton INSTANCE = new Singleton();
   }
 
   public static Singleton getInstance() {
     return SingletonHolder.INSTANCE;
   }
 }

Engineering, Software


 


Comments are closed.