Search This Blog

Wednesday, November 07, 2018

Design Patterns in Java - Singleton

It is a creational design pattern.

Several options(Effective Java pp. 18+) to implement it
o One publicly accessible static instance
• Pros: clarity – obvious that you’re using a shared copy
o One private static instance, accessed with getInstance() 
• Pros: flexibility – could reimplement getInstance() to no longer 
be Singleton
• Nice style – prefer this way for most people
o Enum
• Pros: safer (harder to break Singleton), provides serialization
• But not how Enum is meant to be used
• Josh Bloch recommends this, but we avoid for now unless you like this way.

The Enum-way

In the second edition of his book "Effective Java" Joshua Bloch claims that "a single-element enum type is the best way to implement a singleton" for any Java that supports enums. The use of an enum is very easy to implement and has no drawbacks regarding serializable objects, which have to be circumvented in the other ways.
public enum Singleton {
// other useful methods here


2 types of singleton

You may notice that there is a javax.ejb.Singleton and javax.inject.Singleton. Why two Singleton annotations? A single annotation in CDI lets you define a singleton instance outside of EJB in case you are using CDI in a non-EJB environment. An EJB singleton will have all the features of an EJB such as transaction management so you have the choice depending on your needs and whether the environment is EJB or not.