I am trying to create a singleton class in Java. The best available solution with Java5 and above versions seems to be using enum
. But I am not sure how to convert my class into a singleton class using enum
. Following is my simplified class:
public class Employee {
private int id;
private String name;
public Employee() {}
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getName() {
return name;
}
public void setName( String name ) {
this.name = name;
}
}
When I searched for answers in the net I found the following code:
public enum EasySingleton{
INSTANCE;
}
But where are my class variables and methods? I am not sure how to implement this. I know we can provide methods to enum
but where will my variables go? Any help on this would be really appreciated.
P.S.: Please don't debate if singleton are evil or anti-pattern. I am just curious on how to create a singleton using enum
.