Junior
What are the main two types of implementing the Singleton pattern?
sobes.tech AI
Answer from AI
-
Lazy Initialization: The instance is created upon the first call to the
getInstance()method.public class LazySingleton { private static LazySingleton instance; private LazySingleton() {} public static LazySingleton getInstance() { if (instance == null) { instance = new LazySingleton(); } return instance; } } -
Eager Initialization: The instance is created at the time of class loading.
public class EagerSingleton { private static final EagerSingleton INSTANCE = new EagerSingleton(); private EagerSingleton() {} public static EagerSingleton getInstance() { return INSTANCE; } }