To implement Singleton pattern, we have different approaches :
1.Eager initialization:
In this method the instance of clss is created at loading time .As whenever in java there is a requirement of species at loading time we first remember of Static keyword.
package com.questprogram.singleton; public class EagerInitializedSingleton { private static final EagerInitializedSingleton instance = new EagerInitializedSingleton(); //private constructor to avoid client applications to use constructor private EagerInitializedSingleton(){} public static EagerInitializedSingleton getInstance(){ return instance; } }
2.Static block initialization
Static Block initialization implementation is similar to eager initialization, except that instance of class is created in the static block that provides option for exception handling.
package com.questprogram.singleton; public class StaticBlockSingleton { private static StaticBlockSingleton instance; private StaticBlockSingleton(){} //static block initialization for exception handling static{ try{ instance = new StaticBlockSingleton(); }catch(Exception e){ throw new RuntimeException("Exception occured in creating singleton instance"); } } public static StaticBlockSingleton getInstance(){ return instance; } }
Comments
Post a Comment