如何在Java中为实体实施状态转换? [英] How to implement status transitions for an Entity in java?

查看:187
本文介绍了如何在Java中为实体实施状态转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中有多个实体,例如用户,帐户,许可证等.每个实体都有与之相关的状态,例如有效,正常,已暂停,未验证,待付款,待批准等.我想确保实体可以从预定义状态变为用户"只能从确定"变为暂停",而不能从未验证"变为暂停".实现此目的的最佳设计模式是什么?我环顾四周,主要是找到状态机来解决此类问题,但是由于我不想考虑状态中的事件,因此它们看起来太复杂了.我只想限制国家的过渡.

到目前为止,我可以想到使用预先填充的2D数组,该数组定义每个维度中的所有状态并表示可能的过渡.寻找任何更好的方法.

解决方案

您可以在JPA枚举类型中使用.看看下面的链接. http://tomee.apache.org/examples-trunk/jpa-enumerated/README.html

public enum State {
    STATE1,STATE2(STATE1),STATE3(STATE1,STATE2);

    private State[] previousStates;

    private State(){

    }
    private State(State ...state) {
        this.previousStates =state;
    }

    public State transition(State state) throws Exception {
        for(State tmp: state.previousStates) {
            if (this == tmp) {
                return state;
            }
        }
        throw new Exception("Illegal state");

    }

}

通过在Enum中实现方法转换,您将能够轻松地为JPA中的枚举设置新值,您可以将此调用权限隐藏在set方法中,并且如果状态不正确,它也会抛出Exception./p>

I have multiple entities in my application like Users, Accounts, Licenses etc. Each entity has a status associated with it like Active, Ok, Suspended, Unverified, PendingPayment, PendingApproval etc. I want to make sure the entities can move from a predefined status to another like User can only move from Ok to Suspended but not from Unverified to Suspended. What would be the best design pattern to implement this ? I have looked around and mostly find state machines for such problems, but they look too complex for this as I don't want to consider events in the state. All I want to restrict is the transition of states.

As of now, I can think of using a pre-populated 2D array that defines all statuses in each dimension and represents possible transitions. Looking for any better approaches.

解决方案

You can use in JPA enumerated type. Have a look in the link below. http://tomee.apache.org/examples-trunk/jpa-enumerated/README.html

public enum State {
    STATE1,STATE2(STATE1),STATE3(STATE1,STATE2);

    private State[] previousStates;

    private State(){

    }
    private State(State ...state) {
        this.previousStates =state;
    }

    public State transition(State state) throws Exception {
        for(State tmp: state.previousStates) {
            if (this == tmp) {
                return state;
            }
        }
        throw new Exception("Illegal state");

    }

}

By implementing the method transition within the Enum you will be able to easily set new values for the enum in the JPA you can hide this invocation right into your set method and also it will just throw Exception if the status is incorrect.

这篇关于如何在Java中为实体实施状态转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆