views:

25

answers:

0

I want to implement the state design pattern in JPA. The way I am currently doing this is outlined in this blog post.

The author uses an enum containing all available state implementations instead of creating abstract class/interface for state abstraction and writing implementation for each state. I find this approach very useful, since enums can be easily serialized in JPA and you can store the current state of your object without additional effort. I also nested the state interface and all state classes into the enum making them private, since they are implementation specific and should not be visible to any client. Here's a code example of the enum:

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) {
        // do something
    ctx.setState(STATE_B);
    }

    @Override
    public void transitionB(Context ctx) {
        // do something
    ctx.setState(STATE_A);
    }
  }

  private static class StateB implements StateTransition {

    @Override
    public void transitionA(Context ctx) {
    throw new IllegalStateException("transition not allowed");
    }

    @Override
    public void transitionB(Context ctx) {
        // do something
    ctx.setState(STATE_A);
    }
  }
}

I'd like to and share this with you and get your thoughts on it. Do you find this useful? How would you implement the state design pattern in a JPA domain model?

Thank, Theo