如何在JPA域模型中实现状态设计模式 [英] How to implement the state design pattern in a JPA domain model
问题描述
我想在JPA中实现状态设计模式。我正在这样做的方式在本博客文章
I want to implement the state design pattern in JPA. The way I am currently doing this is outlined in this blog post.
作者使用包含所有可用状态实现的枚举,而不是为每个状态的状态抽象和写入实现创建抽象类/接口。我发现这种方法非常有用,因为枚举可以在JPA中轻松序列化,您可以无需额外的努力来存储对象的当前状态。我也将状态接口和所有状态类嵌套到枚举中,使其成为私有的,因为它们是实现特定的,不应该对任何客户端都可见。这是枚举的代码示例:
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);
}
}
}
我想和与你分享,并得到你的想法。你觉得这有用吗?如何在JPA域模型中实现状态设计模式?
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?
感谢
Theo
Thank, Theo
推荐答案
这是一个古老的问题,但为了那些可能搜索档案的人,我已经使用了带有枚举的弹簧状态机(而不是Strings)。
Well it's an old question, but for the sake of those who might search archives - I have used spring state machine with enums (instead Strings).
关于处理转换,有注释允许在转换发生时调用函数。
Regarding handling transitions, there are annotations that allow your functions to be called when transition happens.
1.1.0.RELEASE给出了一个默认机制,通过持久化StateMachineContext ,另一种使用持续配方。
1.1.0.RELEASE gives a default mechanism to persist a state by persisting StateMachineContext, and an alternative using persist recipe.
现在参考JPA - 可以让Entity Listener在后期(@Postload),我认为这不是很好的路径。
Now refering to JPA - it's possible to have Entity Listener that will initialize statemachine on postload (@Postload), I think it's not good path to go.
这篇关于如何在JPA域模型中实现状态设计模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!