A restricted class only instantiating one object
Contents
Example of Uses
- UI (window manager)
- Service locator
- Logging
- Configuration Classes
Intent
- only one instance of a class is created
- provide a global point of access to the object
Implementation
Lazy initialization
public class Singleton { private static volatile Singleton instance = null; private Singleton() { } public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) instance = new Singleton(); } } return instance; } }
Eager initialization
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("Error occurred!", e); } } private Singleton() {} public static Singleton getInstance() { return instance; } }
Initialization On Demand Holder Idiom
public class Singleton { private Singleton() {} private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton(); } public static Singleton getInstance() { return SingletonHolder.INSTANCE; } }
The Enum way
public enum Singleton { INSTANCE; public void execute (String arg) {} }