Skip to content

Instantly share code, notes, and snippets.

@kevalpatel2106
Created November 29, 2016 09:59
Show Gist options
  • Save kevalpatel2106/2dd5c698db0ad4faf85e0b997e342e1c to your computer and use it in GitHub Desktop.
Save kevalpatel2106/2dd5c698db0ad4faf85e0b997e342e1c to your computer and use it in GitHub Desktop.
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;
}
}
@codefarm0
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment