java版的状态机实现
状态机适⽤场景:
C的操作,需要等到A、B的两个操作(A、B顺序操作),那就需要在 A、B之间创建⼀个状态机(state machine),C的操作需要状态机达到某⼀个状态才能进⾏
1. Overview
java版的状态机的原理其实就是java中的枚举类Enum,所以在进⾏状态机设计之前,先学习⼀下(回顾⼀个java Enum)
2. Java Enums
⼀个简单的例⼦:员⼯请假系统,员⼯到HR那离(submitted)-> 部门领导(Escalated) -> 部门经理(Approved)
public enum LeaveRequestState {
Submitted,
Escalated,
Approved
}
我们可以这样引⽤:
LeaveRequestState state = LeaveRequestState.Submitted;
java的枚举也可以包含⽅法,我们可以在枚举类中写⼀个抽象⽅法(abstract),这样枚举类中的每个成员都会继承该⽅法,这个就是java 版状态机的核⼼所在
public enum LeaveRequestState {
Submitted {
@Override
public String responsiblePerson() {
return "Employee";
}
},
Escalated {
@Override
public String responsiblePerson() {
return "Team Leader";
}
},
Approved {
@Override
public String responsiblePerson() {
return "Department Manager";
}
};
public abstract String responsiblePerson();
}
注意上⾯的逗号,以及抽象⽅法前的分号
在下⾯的例⼦中, 我们使⽤上⾯代码中的responsiblePerson()⽅法. 这就是⼀个典型的状态机. 我们想知道"Escalated "的“状态”(实际是审批⼈), 那就会返回结果 “Team Leader”:
LeaveRequestState state = LeaveRequestState.Escalated;
assertEquals("Team Leader", sponsiblePerson());
同样的 “Department Manager”:
LeaveRequestState state = LeaveRequestState.Approved;
assertEquals("Department Manager", sponsiblePerson());
3. State Machines
状态机⼜称有限状态机,是⼀个建⽴在抽象机器上的计算模型,这个状态机在给定的时间内,只能有⼀个状态,⽽每⼀个状态⼜可以转换为其他状态(其他状态也是我们⾃⼰定义的)
4. Enums as State Machines public enum LeaveRequestState {
Submitted {
@Override
public LeaveRequestState nextState() {
return Escalated;
}
@Override
public String responsiblePerson() {
return "Employee";
}
},
Escalated {
@Override
public LeaveRequestState nextState() {
return Approved;
}
@Override
public String responsiblePerson() {
return "Team Leader";
}
},
Approved {
@Override
public LeaveRequestState nextState() {
return this;
}
@Override
public String responsiblePerson() {
return "Department Manager";
html实现用户注册登录代码}
};
public abstract LeaveRequestState nextState();
public abstract String responsiblePerson();
}
LeaveRequestState state = LeaveRequestState.Submitted; state = State();
assertEquals(LeaveRequestState.Escalated, state);
state = State();
assertEquals(LeaveRequestState.Approved, state);
state = State();
assertEquals(LeaveRequestState.Approved, state);
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论