Last Updated: February 25, 2016
·
4.086K
· eranation

Java Singleton enum

tl;dr

if you have a Java class that has one of the old anti patterns of a singleton (first ask yourself why you need a singleton, but that's a different story)

all you need to do is from this

public class Foo {

  private Foo() {

  }

  public static Foo getInstance() {
    // whatever method you used before
  }

  //class body
}

to this

public enum Foo {
  INSTANCE;

  // class body

  // no need for private constructor
  // no need for getInstance, just use Foo.INSTANCE

}

And that's it.

http://stackoverflow.com/questions/70689/what-is-an-efficient-way-to-implement-a-singleton-pattern-in-java