The accepted way in Java of creating a singleton is with an enum
. This provides thread safe initialisation as well as JVM guaranteed singleton status. There are many ways for creating a second instance of a class
that is not an enum
.
The additional benefit of using an enum
is that you are allowed to case switch on the enum
in your logic:
public enum State {
STATE_A {
@Override
public void doStateDependentLogic(final State newState) {
switch (newState) {
case STATE_B:
//do stuff
//case SOME_OTHER_STATE
}
}
},
STATE_B {
@Override
public void doStateDependentLogic(final State newState) {
}
};
public abstract void doStateDependentLogic(State newState);
}
I don't know where you got the idea that an enum
is a functional programming paradigm. This is not the case. enum
in Java is designed to do exactly what you want.