Singleton
Factory Method
/**
* Description:
* - This class uses eager initialization of singleton instance.
*
*/
public class EagerRegistry {
/**
* Description:
* - By making constructor private, we prevent object instantiation outside of this class
* - this will also prevent inheritance
*
*/
private EagerRegistry() {
}
/**
* Description:
* - The singleton instance
* - Eagerly initialized singleton
*
*/
private static final EagerRegistry INSTANCE = new EagerRegistry();
/**
* Description:
* - This method returns the singleton instance to outside world
* @return Instance of EagerRegistry
*
*/
public static EagerRegistry getInstance() {
return INSTANCE;
}
}
/**
* Description:
* - This class demonstrates singleton pattern using Double Checked Locking or "classic" singleton
* - This is also a lazy initializing singleton
* - Although this implementation solves the multi-threading issue with lazy initialization using volatile
* and double check locking, the volatile keyword is guaranteed to work only after JVMs starting with
* version 1.5 and later.
*
*/
public class LazyRegistryWithDCL {
/**
* Description:
* - Private constructor to prevent instantiation outside this class and prevent subclassing
*/
private LazyRegistryWithDCL() {
}
/**
* Description:
* - The lazy singleton instance
* - Note the use of volatile
*/
private static volatile LazyRegistryWithDCL INSTANCE;
/**
* Description:
* - This method implements the double check locking
* @return Instance of {@link LazyRegistryWithDCL}
*/
public static LazyRegistryWithDCL getInstance() {
if (INSTANCE == null) {
synchronized (LazyRegistryWithDCL.class) {
if (INSTANCE == null) {
INSTANCE = new LazyRegistryWithDCL();
}
}
}
return INSTANCE;
}
}
/**
* Description:
* - Singleton pattern using lazy initialization holder class
* - This ensures that we have a lazy initialization without worrying about synchronization
*
*/
public class LazyRegistryIODH {
/**
* Description:
* - Private constructor to prevent instantiation outside of this class
* - This also prevents inheritance
*/
private LazyRegistryIODH() {
System.out.println("In LazyRegistryIODH singleton");
}
/**
* Description:
* - This class provides with the Initialization on demand holder pattern
*/
private static class RegistryHolder {
static LazyRegistryIODH INSTANCE = new LazyRegistryIODH();
}
/**
* Description:
* - This method provides the singleton instance. Note the use of {@link RegistryHolder}
* @return Instance of {@link LazyRegistryIODH}
*/
public static LazyRegistryIODH getInstance() {
return RegistryHolder.INSTANCE;
}
}