Created
August 18, 2022 08:36
-
-
Save evrentan/f04b9c2f0d3920572379ccb208dc33da to your computer and use it in GitHub Desktop.
Lazy Instantiation of Singleton Design Pattern in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package example.dto; | |
import java.time.LocalTime; | |
import java.util.Objects; | |
public class LazyInstantiationOfSingletonClass { | |
/** | |
* Static attribute to be sure that it is loaded once | |
*/ | |
private static LazyInstantiationOfSingletonClass lazyInstantiationOfSingletonClass; | |
/** | |
* Private constructor to avoid instantiate the class from outside the class | |
* | |
* @author <a href="https://github.com/evrentan">Evren Tan</a> | |
*/ | |
private LazyInstantiationOfSingletonClass() { | |
} | |
/** | |
* Static factory method that returns the object. It checks whether it is instantiated or not. If not, it creates the object first. | |
* @return LazyInstantiationOfSingletonClass instance | |
* | |
* @author <a href="https://github.com/evrentan">Evren Tan</a> | |
*/ | |
public static LazyInstantiationOfSingletonClass getInstance() { | |
// object is instantiated at call time of getInstance() method | |
if (Objects.isNull(lazyInstantiationOfSingletonClass)) { | |
lazyInstantiationOfSingletonClass = new LazyInstantiationOfSingletonClass(); | |
System.out.println(String.format("%s is instantiated at call time at %s !!!", LazyInstantiationOfSingletonClass.class.getCanonicalName(), LocalTime.now())); | |
} | |
return lazyInstantiationOfSingletonClass; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment