Created
November 29, 2016 09:59
-
-
Save kevalpatel2106/2dd5c698db0ad4faf85e0b997e342e1c to your computer and use it in GitHub Desktop.
This file contains 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
public class SingletonClass { | |
private static SingletonClass sSoleInstance; | |
//private constructor. | |
private SingletonClass(){ | |
//Prevent form the reflection api. | |
if (sSoleInstance != null){ | |
throw new RuntimeException("Use getInstance() method to get the single instance of this class."); | |
} | |
} | |
public static SingletonClass getInstance(){ | |
if (sSoleInstance == null){ //if there is no instance available... create new one | |
sSoleInstance = new SingletonClass(); | |
} | |
return sSoleInstance; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Singleton contract is breakable by reflection.
As sSoleInstance not getting initialized when instance is created from reflection only and eveytime it will be not null and new instance created.
https://medium.com/@kevalpatel2106/how-to-make-the-perfect-singleton-de6b951dfdb0