Mina状态机StateMachine

首先,关于状态机的一个极度确切的描述是它是一个有向图形,由一组节点和一组相应的转移函数组成。状态机通过响应一系列事件而“运行”。每个事件都在属于“当前” 节点的转移函数的控制范围内,其中函数的范围是节点的一个子集。函数返回“下一个”(也许是同一个)节点。这些节点中至少有一个必须是终态。当到达终态, 状态机停止。

接下来的问题是,我们为什么要用状态机,什么时候用:

传统应用程序的控制流程基本是顺序的:遵循事先设定的逻辑,从头到尾地执行。很少有事件能改变标准执行流程;而且这些事件主要涉及异常情况。“命令行实用程序”是这种传统应用程序的典型例子。

另一类应用程序由外部发生的事件来驱动——换言之,事件在应用程序之外生成,无法由应用程序或程序员来控制。具体需要执行的代码取决于接收到的事件,或者它 相对于其他事件的抵达时间。所以,控制流程既不能是顺序的,也不能是事先设定好的,因为它要依赖于外部事件。事件驱动的GUI应用程序是这种应用程序的典 型例子,它们由命令和选择(也就是用户造成的事件)来驱动。

下面我们看个mina-statemachine的简单例子。 

The picture below shows a state machine for a typical tape deck. The ellipsis is the states while the arrows are the transitions. Each transition is labeled with an event name which triggers that transition.

状态机可归纳为4个要素,即现态、条件、动作、次态。

下面用代码来实现这一过程,首先我们定义动作接口:

package com.xjtu.cruise.mina;
/**
 * 动作接口
 * 2013年11月6日 
 * @author cruise
 *
 */
public interface TapeDeck {
	void load(String nameOfTape);

	void eject();

	void play();

	void pause();

	void stop();
}

Tape Deck就是老式的录音机的意思。而动作接口,就相当于录音机外面的几个按钮。接下来我们定义状态:

package com.xjtu.cruise.mina;

import org.apache.mina.statemachine.annotation.State;
import org.apache.mina.statemachine.annotation.Transition;
import org.apache.mina.statemachine.annotation.Transitions;
/**
 * 定义状态
 * 2013年11月6日 18:48:59
 * @author cruise
 *
 */

public class TapeDeckHandler {
	@State
	public static final String EMPTY = "Empty";
	@State
	public static final String LOADED = "Loaded";
	@State
	public static final String PLAYING = "Playing";
	@State
	public static final String PAUSED = "Paused";

	@Transition(on = "load", in = EMPTY, next = LOADED)
	public void loadTape(String nameOfTape) {
		System.out.println("Tape '" + nameOfTape + "' loaded");
	}

	@Transitions({ @Transition(on = "play", in = LOADED, next = PLAYING),
			@Transition(on = "play", in = PAUSED, next = PLAYING) })
	public void playTape() {
		System.out.println("Playing tape");
	}

	@Transition(on = "pause", in = PLAYING, next = PAUSED)
	public void pauseTape() {
		System.out.println("Tape paused");
	}

	@Transition(on = "stop", in = PLAYING, next = LOADED)
	public void stopTape() {
		System.out.println("Tape stopped");
	}

	@Transition(on = "eject", in = LOADED, next = EMPTY)
	public void ejectTape() {
		System.out.println("Tape ejected");
	}
}

状态即现态。在Transition Annotation中的on表示动作的ID,对应着动作接口中的方法名,in表示的是动作的起始状态,next表示的是动作的后续状态。

这里要注意以下几点:

More about the @Transition parameters
•	If you omit the on parameter it will default to "*" which will match any event.
•	If you omit the next parameter it will default to "_self_" which is an alias for the current state. To create a loop transition in your state machine all you have to do is to omit the next parameter.
•	The weight parameter can be used to define in what order transitions will be searched. Transitions for a particular state will be ordered in ascending order according to their weight value. weight is 0 by default.

最后我们看一下测试类:

package com.xjtu.cruise.mina;

import org.apache.mina.statemachine.StateMachine;
import org.apache.mina.statemachine.StateMachineFactory;
import org.apache.mina.statemachine.StateMachineProxyBuilder;
import org.apache.mina.statemachine.annotation.Transition;

public class Test {
	public static void main(String[] args) {

		TapeDeckHandler handler = new TapeDeckHandler();
		StateMachine sm = StateMachineFactory.getInstance(Transition.class)
				.create(TapeDeckHandler.EMPTY, handler);
		TapeDeck deck = new StateMachineProxyBuilder().create(TapeDeck.class,
				sm);

		deck.load("Kiss Goodbye-Lee Hom");
		deck.play();
		deck.pause();
		deck.play();
		deck.stop();
		deck.eject();
	}
}

运行结果正确,按着我们放置录音的想法来的。如果,我们调换其中的一个顺序,当然不符合我的逻辑:

deck.load("Kiss Goodbye-Lee Hom");
		    deck.play();
		    deck.pause();
		    deck.play();
		    deck.stop();
		    deck.pause();/**stop-->pause org.apache.mina.statemachine.event.UnhandledEventException*/
		    deck.eject();

这样程序就报错了,所以mina的状态机帮我们很方便的调控了事件发生的状态。

我们来看一下mina状态机实现的一些细节:

1.    Lookup a StateContext Object

       The StateContext object is important because it holds the current State. When a method is called on the proxy it will ask aStateContextLookup instance to get the StateContext from the method's arguments. Normally, the StateContextLookup implementation will loop through the method arguments and look for a particular type of object and use it to retrieve a StateContext object. If noStateContext has been assigned yet the StateContextLookup will create one and store it in the object.

2.    Convert the method invocation into an Event object

All method invocations on the proxy object will be translated into Event objects by the proxy. An Event has an id and zero or more arguments. The id corresponds to the name of the method and the event arguments correspond to the method arguments. The method call deck.load("The Knife - Silent Shout") corresponds to the event {id = "load", arguments = ["The Knife - Silent Shout"]}. The Event object also contains a reference to the StateContext object looked up previously.

3.    Invoke the StateMachine

Once the Event object has been created the proxy will call StateMachine.handle(Event). StateMachine.handle(Event) loops through the Transition objects of the current State in search for a Transition instance which accepts the current Event. This process will stop after a Transition has been found. The Transition objects will be searched in order of weight (typically specified by the@Transition  annotation).

4.    Execute the Transition

The final step is to call Transition.execute(Event) on the Transition which matched the Event. After the Transition has been executed the StateMachine will update the current State with the end state defined by the Transition.



上面只是用mina实现了一个最简单的状态机,通过这个例子我们可以大概的了解到了状态机的执行过程,当然基于Annotation这样的方式我们用最基本的代码也能实现出来。参见下一篇

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值