Singleton

Lazy initialization

public class SingletonDemo {
    private static volatile SingletonDemo instance;
    private SingletonDemo() { }

    public static SingletonDemo getInstance() {
        if (instance == null ) {
            synchronized (SingletonDemo.class) {
                if (instance == null) {
                    instance = new SingletonDemo();
                }
            }
        }

        return instance;
    }
} 
 

Eager initialization - using static factory method

public class Singleton {
    private static final Singleton INSTANCE = new Singleton();

    private Singleton() {}

    public static Singleton getInstance() {
        return INSTANCE;
    }
}
 

Static block initialization

public class Singleton {
    private static final Singleton instance;

    static {
        try {
            instance = new Singleton();
        } catch (Exception e) {
            throw new RuntimeException("Darn, an error occurred!", e);
        }
    }

    public static Singleton getInstance() {
        return instance;
    }

    private Singleton() {
        // ...
    }
}

 

Initialization-on-demand holder 

public class Singleton {
        // Private constructor. Prevents instantiation from other classes.
        private Singleton() { }

        /**
         * Initializes singleton.
         *
         * {@link SingletonHolder} is loaded on the first execution of {@link Singleton#getInstance()} or the first access to
         * {@link SingletonHolder#INSTANCE}, not before.
         */
        private static class SingletonHolder {
                private static final Singleton INSTANCE = new Singleton();
        }

        public static Singleton getInstance() {
                return SingletonHolder.INSTANCE;
        }
}
 
 
 

Handle Serialization - readResolve()

 //readResolve to prevent another instance of Singleton

    private Object readResolve(){

        return INSTANCE;

    }

 

Uasing ENUM

 
public enum AnimalHelperSingleton {

    INSTANCE;

    private AnimalHelperSingleton(){

    }
 
   /**Add some behavior to the object. */
    public Animal[] buildAnimalList(){
        final Animal[] animals = new Animal[10];

        animals[0] = new SimpleAnimal(Animal.AnimalClass.MAMMAL, 
                "Dog", true, Color.GRAY);
        animals[1] = new SimpleAnimal(Animal.AnimalClass.MAMMAL, 
                "Cat", true, Color.YELLOW);
        animals[2] = new SimpleAnimal(Animal.AnimalClass.AMPHIBIAN,
                "Frog", true, Color.GREEN);
        animals[3] = new SimpleAnimal(Animal.AnimalClass.BIRD,
                "Crow", true, Color.BLACK);
        animals[4] = new SimpleAnimal(Animal.AnimalClass.BIRD,
                "Cardinal", true, Color.RED);
        animals[5] = new SimpleAnimal(Animal.AnimalClass.ARTHROPOD,
                "Mantis", false, Color.GREEN);
        animals[6] = new SimpleAnimal(Animal.AnimalClass.ARTHROPOD,
                "Spider", false, Color.ORANGE);
        animals[7] = new SimpleAnimal(Animal.AnimalClass.MAMMAL, 
                "Tiger", true, Color.ORANGE);
        animals[8] = new SimpleAnimal(Animal.AnimalClass.MAMMAL, 
                "Bear", true, Color.BLACK);
        animals[9] = new SimpleAnimal(Animal.AnimalClass.BIRD, 
                "Owl", true, Color.BLACK);

        return animals;
    }

}  
//Call singleton to build the animal list.
Animal[] animals = AnimalHelperSingleton.INSTANCE.buildAnimalList();

OR

/** Preferred style for singletons. */
public enum SantaClaus {
  INSTANCE;
  
  /**Add some behavior to the object. */
  public void distributePresents(){
    //elided    
  }
  
  /** Demonstrate use of SantaClaus. */
  public static void main(String... aArgs){
    SantaClaus fatGuy = SantaClaus.INSTANCE;
    fatGuy.distributePresents();
    
    //doesn't compile :
    //SantaClaus fatGuy = new SantaClaus();
  }
} 

 

 

 

 

0 comments: