Skip to content

Instantly share code, notes, and snippets.

@daveRanjan
Created November 1, 2016 14:00
Show Gist options
  • Save daveRanjan/24932df9740e393656492c136431208c to your computer and use it in GitHub Desktop.
Save daveRanjan/24932df9740e393656492c136431208c to your computer and use it in GitHub Desktop.
A very simple explaned example of singleton class
class Singleton {
// This is an object of the same class, but give more attention towards
// private :- This object cannot be accessed from outside, you have use getter (getInstance) method
// static :- This object is static as getInstance have to be static (Why?? You'll know) and
// only static variables can be accessed in static methods
private static Singleton INSTANCE = null;
// Ofcourse a class is of no use if it does not have any data (So this is the data for which every thread will fight)
private String criticalData;
// Again look at private, (What the hell?? A private constructor), so basically it is done so that nobody should
// be able to access this constructor from outside the class. We will use this in getInstance method. And that method
// will expose it to the world
private Singleton() {
criticalData = "This should be unique and state should be universal";
}
// Here comes the hero of our story. THE getInstance() method.
// So ofcourse it returns an object of the same class (how else it will return Instance :D )
// but what about other two keywords :-
// synchronized :- It ensures that only one thread will be calling this method at a time.
// static :- It ensures that an object of Singleton class is not required to invoke this method. it can be directly
// access like this Singleton.getInstance()
synchronized static Singleton getInstance() {
// it says, create a instance of Singleton class only if it doesn't exists.
// there is also another concept hidden in below lines it called Lazy init
// which basiscally means that an instance of this class will be created untill
// it is called.
if (INSTANCE == null) {
//create an instance if no previous instance is created
INSTANCE = new Singleton();
}
// on this line, it will always have an instance of the class.
return INSTANCE;
}
// These method need not be static (why? you tell me in comments )
public String getString() {
return this.criticalData;
}
public void setCriticalData(String value) {
criticalData = value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment