I want to implement a state design template in JPA. The way I do it now is outlined in this post.
The author uses an enumeration containing all available implementations, instead of creating an abstract class / interface to abstract the state and write the implementation for each state. I find this approach very useful, since enumerations can be easily serialized in JPA, and you can save the current state of your object without extra effort. I also nested the state interface and all state classes in enum, making them private, as they are implementation specific and should not be visible to any client. Here is an example enumeration code:
public enum State { STATE_A(new StateA()), STATE_B(new StateB()); private final StateTransition state; private State(StateTransition state) { this.state = state; } void transitionA(Context ctx) { state.transitionA(ctx); } void transitionB(Context ctx) { state.transitionB(ctx); } private interface StateTransition { void transitionA(Context ctx); void transitionB(Context ctx); } private static class StateA implements StateTransition { @Override public void transitionA(Context ctx) {
I would like to share this with you and talk about it. Do you find this helpful? How to implement a state design pattern in a JPA domain model?
Thanks Theo
source share