Skip to content

Instantly share code, notes, and snippets.

@slmanju
Created January 25, 2018 03:51
Show Gist options
  • Save slmanju/9989df8293697f89c30fd7f90bc69cce to your computer and use it in GitHub Desktop.
Save slmanju/9989df8293697f89c30fd7f90bc69cce to your computer and use it in GitHub Desktop.
Singleton design pattern with Java
public class SingletonEager {
private static final SingletonEager INSTANCE = new SingletonEager();
private SingletonEager() {
System.out.println("in the constructor"); // this will print first
}
public static SingletonEager getInstance() {
return INSTANCE;
}
public void print() {
System.out.println("hello from eager");
}
public static void main(String[] args) {
System.out.println("main method start");
SingletonEager.getInstance().print();;
System.out.println("main end");
}
}
/**
* Bill Pugh method
* Lazily initialized since holder is an inner class and only created when getInstance() method is called.
*
*/
public class SingletonHolder {
private SingletonHolder() {
System.out.println("in the constructor");
}
private static class Holder {
private static final SingletonHolder INSTANCE = new SingletonHolder();
}
public static SingletonHolder getInstance() {
return Holder.INSTANCE;
}
public void print() {
System.out.println("hello from holder");
}
public static void main(String[] args) {
System.out.println("main method start");
SingletonHolder.getInstance().print();
System.out.println("main end");
}
}
public class SingletonLazy {
private static SingletonLazy instance = null;
private SingletonLazy() {
System.out.println("in the constructor");
}
public static SingletonLazy getInstance() {
if (instance == null) {
// synchronized block to remove overhead
synchronized (SingletonLazy.class) {
if (instance == null) {
// if instance is null, initialize
instance = new SingletonLazy();
}
}
}
return instance;
}
public void print() {
System.out.println("hello from lazy");
}
public static void main(String[] args) {
System.out.println("main method start");
SingletonLazy.getInstance().print();
System.out.println("main end");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment