Sobes.tech
Junior

What are the main two types of implementing the Singleton pattern?

sobes.tech AI

Answer from AI

  1. 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;
        }
    }
    
  2. 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;
        }
    }
    
What are the main two types of implementing the… - sobes.tech