Skip to content

Instantly share code, notes, and snippets.

@saishaddai
Last active August 29, 2015 13:57
Show Gist options
  • Save saishaddai/9417900 to your computer and use it in GitHub Desktop.
Save saishaddai/9417900 to your computer and use it in GitHub Desktop.
Singleton in Java
//OPTION 1 using enums
//Each element in the enum is unique and keep their last modified values
//even when used by threads the values of the elements are the same
//they can be accessed via Currentcy.DIME and so
//everytime you instance class Animal, the values keep the last state they were
public enum Animal {
CAT("meow"), DOG("bark"), ELEPHANT("WTF"), HUMAN("talk");
}
//OPTION2 using static/synchronized
//Everytime you call the getInstance method you'll get the last state of the Animal class
//Only the first time, you'll get a brand new Animal class
//The latter times you call it, it will keep tha last state of the instance
public class Animal {
private static Animal uniqInstance;
private Animal() {
}
public static synchronized Animal getInstance() {
if (uniqInstance == null) {
uniqInstance = new Animal();
}
return uniqInstance;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment