有限状态机 java_AKKA文档(Java版)—建立有限状态机角色

状态应该如何处理

FSM角色实现引用的所有可变字段(或可传递的可变数据结构)应该被收集在一个地方及仅通过使用小粒度的的定义良好的一组方法来改变。要做到这一点的一种实现方法是集合所有可变状态在一个超类中,并且保持其的私有及为改变其提供保护方法。

import java.util.ArrayList;

import java.util.List;

import akka.actor.ActorRef;

public abstract class MyFSMBase extends UntypedActor {

/*

* This is the mutable state of this state machine.

*/

protected enum State {

IDLE, ACTIVE;

}

private State state = State.IDLE;

private ActorRef target;

private List queue;

/*

* Then come all the mutator methods:

*/

protected void init(ActorRef target) {

this.target = target;

queue = new ArrayList();

}

protected void setState(State s) {

if (state != s) {

transition(state, s);

state = s;

}

}

protected void enqueue(Object o) {

if (queue != null)

queue.add(o);

}

protected List drainQueue() {

final List q = queue;

if (q == null)

throw new IllegalStateException("drainQueue(): not yet initialized");

queue = new ArrayList();

return q;

}

/*

* Here are the interrogation methods:

*/

protected boolean isInitialized() {

return target != null;

}

protected State getState() {

return state;

}

protected ActorRef getTarget() {

if (target == null)

throw new IllegalStateException("getTarget(): not yet initialized");

return target;

}

/*

* And finally the callbacks (only one in this example: react to state change)

*/

abstract protected void transition(State old, State next);

}

上面方法好处是状态改变可以表现在一个中心位置之上,当添加到FSM机器时,这使得它不可能忘记插入代码对于状态转变的反应。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值