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

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

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

另一类应用程序由外部发生的事件来驱动——换言之,事件在应用程序之外生成,无法由应用程序或程序员来控制。具体需要执行的代码取决于接收到的事件,或者 它 相对于其他事件的抵达时间。所以,控制流程既不能是顺序的,也不能是事先设定好的,因为它要依赖于外部事件。事件驱动的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.

Mina状态机State Machine_desktop

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

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

01 package com.a2.desktop.example9.mina.statemachine;
02  
03 /**
04  * 动作接口
05  *
06  * @author ChenHui
07  *
08  */
09 public interface TapeDeck {
10      
11     void load(String nameOfTape);
12  
13     void eject();
14  
15     void play();
16  
17     void pause();
18  
19     void stop();
20 }

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

01 package com.a2.desktop.example9.mina.statemachine;
02  
03 import org.apache.mina.statemachine.annotation.State;
04 import org.apache.mina.statemachine.annotation.Transition;
05 import org.apache.mina.statemachine.annotation.Transitions;
06  
07 /**
08  * 定义状态
09  *
10  * @author ChenHui
11  *
12  */
13 public class TapeDeckHandler {
14     @State
15     public static final String EMPTY = "Empty";
16     @State
17     public static final String LOADED = "Loaded";
18     @State
19     public static final String PLAYING = "Playing";
20     @State
21     public static final String PAUSED = "Paused";
22  
23     @Transition(on = "load", in = EMPTY, next = LOADED)
24     public void loadTape(String nameOfTape) {
25         System.out.println("Tape '" + nameOfTape + "' loaded");
26     }
27  
28     @Transitions({
29         @Transition(on = "play", in = LOADED, next = PLAYING),
30         @Transition(on = "play", in = PAUSED, next = PLAYING)
31     })
32     public void playTape() {
33         System.out.println("Playing tape");
34     }
35  
36     @Transition(on = "pause", in = PLAYING, next = PAUSED)
37     public void pauseTape() {
38         System.out.println("Tape paused");
39     }
40  
41     @Transition(on = "stop", in = PLAYING, next = LOADED)
42     public void stopTape() {
43         System.out.println("Tape stopped");
44     }
45  
46     @Transition(on = "eject", in = LOADED, next = EMPTY)
47     public void ejectTape() {
48         System.out.println("Tape ejected");
49     }
50 }

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

这里要注意以下几点:

1 More about the @Transition parameters
2 •   If you omit the on parameter it will default to "*" which will match any event.
3 •   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.
4 •   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.

最后我们看一下测试类:

01 package com.a2.desktop.example9.mina.statemachine;
02  
03 import org.apache.mina.statemachine.StateMachine;
04 import org.apache.mina.statemachine.StateMachineFactory;
05 import org.apache.mina.statemachine.StateMachineProxyBuilder;
06 import org.apache.mina.statemachine.annotation.Transition;
07  
08 public class Test {
09      
10         public static void main(String[] args) {
11              
12             TapeDeckHandler handler = new TapeDeckHandler();
13             StateMachine sm = StateMachineFactory.getInstance(Transition.class).create(TapeDeckHandler.EMPTY, handler);
14             TapeDeck deck = new StateMachineProxyBuilder().create(TapeDeck.class, sm);
15              
16             deck.load("Kiss Goodbye-Lee Hom");
17             deck.play();
18             deck.pause();
19             deck.play();
20             deck.stop();
21             deck.eject();
22         }
23     }

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

1 deck.load("Kiss Goodbye-Lee Hom");
2             deck.play();
3             deck.pause();
4             deck.play();
5             deck.stop();
6             deck.pause();/**stop-->pause org.apache.mina.statemachine.event.UnhandledEventException*/
7             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这样的方式我们用最基本的代码也能实现出来。接下来我们要把这样的方式用在通信中。用通信的方式来模拟录放机的按钮。

我们先看状态的定义:

001 package com.a2.desktop.example10.mina.statemachine;
002  
003 import static org.apache.mina.statemachine.event.IoHandlerEvents.EXCEPTION_CAUGHT;
004 import static org.apache.mina.statemachine.event.IoHandlerEvents.MESSAGE_RECEIVED;
005 import static org.apache.mina.statemachine.event.IoHandlerEvents.SESSION_OPENED;
006  
007 import org.apache.mina.core.future.IoFutureListener;
008 import org.apache.mina.core.session.IoSession;
009  
010 import org.apache.mina.statemachine.StateControl;
011 import org.apache.mina.statemachine.annotation.IoHandlerTransition;
012 import org.apache.mina.statemachine.annotation.IoHandlerTransitions;
013 import org.apache.mina.statemachine.annotation.State;
014 import org.apache.mina.statemachine.context.AbstractStateContext;
015 import org.apache.mina.statemachine.context.StateContext;
016 import org.apache.mina.statemachine.event.Event;
017  
018 public class TapeDeckServer {
019  
020     @State
021     public static final String ROOT = "Root";
022     @State(ROOT)
023     // 表示继承关系
024     public static final String EMPTY = "Empty";
025     @State(ROOT)
026     public static final String LOADED = "Loaded";
027     @State(ROOT)
028     public static final String PLAYING = "Playing";
029     @State(ROOT)
030     public static final String PAUSED = "Paused";
031  
032     private final String[] tapes = { "盖世英雄-王力宏", "唯一-王力宏" };
033  
034     static class TapeDeckContext extends AbstractStateContext {
035         public String tapeName;
036     }
037      
038      @IoHandlerTransition(on = SESSION_OPENED, in = EMPTY)
039         public void connect(IoSession session) {
040             session.write("+ Greetings from your tape deck!");
041         }
042          
043         @IoHandlerTransition(on = MESSAGE_RECEIVED, in = EMPTY, next = LOADED)
044         public void loadTape(TapeDeckContext context, IoSession session, LoadCommand cmd) {
045       
046             if (cmd.getTapeNumber() < 1 || cmd.getTapeNumber() > tapes.length) {
047                 session.write("- Unknown tape number: " + cmd.getTapeNumber());
048                 StateControl.breakAndGotoNext(EMPTY);
049             } else {
050                 context.tapeName = tapes[cmd.getTapeNumber() - 1];
051                 session.write("+ \"" + context.tapeName + "\" loaded");
052             }
053         }
054  
055         @IoHandlerTransitions({
056             @IoHandlerTransition(on = MESSAGE_RECEIVED, in = LOADED, next = PLAYING),
057             @IoHandlerTransition(on = MESSAGE_RECEIVED, in = PAUSED, next = PLAYING)
058         })
059         public void playTape(TapeDeckContext context, IoSession session, PlayCommand cmd) {
060             session.write("+ Playing \"" + context.tapeName + "\"");
061         }
062          
063         @IoHandlerTransition(on = MESSAGE_RECEIVED, in = PLAYING, next = PAUSED)
064         public void pauseTape(TapeDeckContext context, IoSession session, PauseCommand cmd) {
065             session.write("+ \"" + context.tapeName + "\" paused");
066         }
067          
068         @IoHandlerTransition(on = MESSAGE_RECEIVED, in = PLAYING, next = LOADED)
069         public void stopTape(TapeDeckContext context, IoSession session, StopCommand cmd) {
070             session.write("+ \"" + context.tapeName + "\" stopped");
071         }
072          
073         @IoHandlerTransition(on = MESSAGE_RECEIVED, in = LOADED, next = EMPTY)
074         public void ejectTape(TapeDeckContext context, IoSession session, EjectCommand cmd) {
075             session.write("+ \"" + context.tapeName + "\" ejected");
076             context.tapeName = null;
077         }
078          
079         @IoHandlerTransition(on = MESSAGE_RECEIVED, in = ROOT)
080         public void listTapes(IoSession session, ListCommand cmd) {
081             StringBuilder response = new StringBuilder("+ (");
082             for (int i = 0; i < tapes.length; i++) {
083                 response.append(i + 1).append(": ");
084                 response.append('"').append(tapes[i]).append('"');
085                 if (i < tapes.length - 1) {
086                     response.append(", ");
087                 }
088             }
089             response.append(')');
090             session.write(response);
091         }
092          
093         @IoHandlerTransition(on = MESSAGE_RECEIVED, in = ROOT)
094         public void info(TapeDeckContext context, IoSession session, InfoCommand cmd) {
095             String state = context.getCurrentState().getId().toLowerCase();
096             if (context.tapeName == null) {
097                 session.write("+ Tape deck is " + state + "");
098             } else {
099                 session.write("+ Tape deck is " + state
100                         + ". Current tape: \"" + context.tapeName + "\"");
101             }
102         }
103          
104         @IoHandlerTransition(on = MESSAGE_RECEIVED, in = ROOT)
105         public void quit(TapeDeckContext context, IoSession session, QuitCommand cmd) {
106             session.write("+ Bye! Please come back!").addListener(IoFutureListener.CLOSE);
107         }
108          
109         @IoHandlerTransition(on = MESSAGE_RECEIVED, in = ROOT, weight = 10)
110         public void error(Event event, StateContext context, IoSession session, Command cmd) {
111             session.write("- Cannot " + cmd.getName()
112                     + " while " + context.getCurrentState().getId().toLowerCase());
113         }
114          
115         @IoHandlerTransition(on = EXCEPTION_CAUGHT, in = ROOT)
116         public void commandSyntaxError(IoSession session, CommandSyntaxException e) {
117             session.write("- " + e.getMessage());
118         }
119          
120         @IoHandlerTransition(on = EXCEPTION_CAUGHT, in = ROOT, weight = 10)
121         public void exceptionCaught(IoSession session, Exception e) {
122             e.printStackTrace();
123             session.close(true);
124         }
125          
126         @IoHandlerTransition(in = ROOT, weight = 100)
127         public void unhandledEvent() {
128         }
129          
130 }

命令的抽象类:

1 package com.a2.desktop.example10.mina.statemachine;
2  
3 public abstract class Command {
4      public abstract String getName();
5 }

以下是各类命令,实现形式相似:

01 package com.a2.desktop.example10.mina.statemachine;
02  
03 public class LoadCommand extends Command {
04      
05     public static final String NAME = "load";
06  
07     private final int tapeNumber;
08  
09     public LoadCommand(int tapeNumber) {
10         this.tapeNumber = tapeNumber;
11     }
12  
13     public int getTapeNumber() {
14         return tapeNumber;
15     }
16  
17     @Override
18     public String getName() {
19         return NAME;
20     }
21  
22 }
23  
24 package com.a2.desktop.example10.mina.statemachine;
25  
26 public class PlayCommand extends Command {
27  
28     public static final String NAME = "play";
29  
30     @Override
31     public String getName() {
32         return NAME;
33     }
34 }
35 //以下省略各种命令…

下面是解码器,继承了文本的解码方式:

01 package com.a2.desktop.example10.mina.statemachine;
02  
03 import java.nio.charset.Charset;
04 import java.util.LinkedList;
05  
06 import org.apache.mina.core.buffer.IoBuffer;
07 import org.apache.mina.core.filterchain.IoFilter.NextFilter;
08 import org.apache.mina.core.session.IoSession;
09 import org.apache.mina.filter.codec.ProtocolDecoderOutput;
10 import org.apache.mina.filter.codec.textline.LineDelimiter;
11 import org.apache.mina.filter.codec.textline.TextLineDecoder;
12  
13 public class CommandDecoder extends TextLineDecoder {
14  
15      public CommandDecoder() {
16             super(Charset.forName("UTF8"), LineDelimiter.WINDOWS);
17         }
18          
19         private Object parseCommand(String line) throws CommandSyntaxException {
20             String[] temp = line.split(" +", 2);
21             String cmd = temp[0].toLowerCase();
22             String arg = temp.length > 1 ? temp[1] : null;
23              
24             if (LoadCommand.NAME.equals(cmd)) {
25                 if (arg == null) {
26                     throw new CommandSyntaxException("No tape number specified");
27                 }
28                 try {
29                     return new LoadCommand(Integer.parseInt(arg));
30                 } catch (NumberFormatException nfe) {
31                     throw new CommandSyntaxException("Illegal tape number: " + arg);
32                 }
33             } else if (PlayCommand.NAME.equals(cmd)) {
34                 return new PlayCommand();
35             } else if (PauseCommand.NAME.equals(cmd)) {
36                 return new PauseCommand();
37             } else if (StopCommand.NAME.equals(cmd)) {
38                 return new StopCommand();
39             } else if (ListCommand.NAME.equals(cmd)) {
40                 return new ListCommand();
41             } else if (EjectCommand.NAME.equals(cmd)) {
42                 return new EjectCommand();
43             } else if (QuitCommand.NAME.equals(cmd)) {
44                 return new QuitCommand();
45             } else if (InfoCommand.NAME.equals(cmd)) {
46                 return new InfoCommand();
47             }
48              
49             throw new CommandSyntaxException("Unknown command: " + cmd);
50         }
51  
52         @Override
53         public void decode(IoSession session, IoBuffer in, final ProtocolDecoderOutput out)
54                 throws Exception {
55              
56             final LinkedList<String> lines = new LinkedList<String>();
57             super.decode(session, in, new ProtocolDecoderOutput() {
58                 public void write(Object message) {
59                     lines.add((String) message);
60                 }
61                 public void flush(NextFilter nextFilter, IoSession session) {}
62             });
63              
64             for (String s: lines) {
65                 out.write(parseCommand(s));
66             }
67         }
68 }

处理异常类:

01 package com.a2.desktop.example10.mina.statemachine;
02  
03 import org.apache.mina.filter.codec.ProtocolDecoderException;
04  
05 /**
06  * Exception thrown by CommandDecoder when a line cannot be decoded as a Command
07  * object.
08  *
09  */
10 public class CommandSyntaxException extends ProtocolDecoderException {
11     private final String message;
12  
13     public CommandSyntaxException(String message) {
14         super(message);
15         this.message = message;
16     }
17  
18     @Override
19     public String getMessage() {
20         return message;
21     }
22 }
测试类:
01 package com.a2.desktop.example10.mina.statemachine;
02  
03 import java.net.InetSocketAddress;
04  
05 import org.apache.mina.core.service.IoHandler;
06 import org.apache.mina.filter.codec.ProtocolCodecFilter;
07 import org.apache.mina.filter.codec.textline.TextLineEncoder;
08 import org.apache.mina.filter.logging.LoggingFilter;
09 import org.apache.mina.statemachine.StateMachine;
10 import org.apache.mina.statemachine.StateMachineFactory;
11 import org.apache.mina.statemachine.StateMachineProxyBuilder;
12 import org.apache.mina.statemachine.annotation.IoHandlerTransition;
13 import org.apache.mina.statemachine.context.IoSessionStateContextLookup;
14 import org.apache.mina.statemachine.context.StateContext;
15 import org.apache.mina.statemachine.context.StateContextFactory;
16 import org.apache.mina.transport.socket.SocketAcceptor;
17 import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
18  
19 public class TestMain {
20      private static final int PORT = 8082;
21          
22         private static IoHandler createIoHandler() {
23             StateMachine sm = StateMachineFactory.getInstance(
24                     IoHandlerTransition.class).create(TapeDeckServer.EMPTY,
25                     new TapeDeckServer());
26  
27             return new StateMachineProxyBuilder().setStateContextLookup(
28                     new IoSessionStateContextLookup(new StateContextFactory() {
29                         public StateContext create() {
30                             return new TapeDeckServer.TapeDeckContext();
31                         }
32                     })).create(IoHandler.class, sm);
33         }
34          
35         public static void main(String[] args) throws Exception {
36             SocketAcceptor acceptor = new NioSocketAcceptor();
37             acceptor.setReuseAddress(true);
38             ProtocolCodecFilter pcf = new ProtocolCodecFilter(
39                     new TextLineEncoder(), new CommandDecoder());
40             acceptor.getFilterChain().addLast("log1", new LoggingFilter("log1"));
41             acceptor.getFilterChain().addLast("codec", pcf);
42             acceptor.getFilterChain().addLast("log2", new LoggingFilter("log2"));
43             acceptor.setHandler(createIoHandler());
44             acceptor.bind(new InetSocketAddress(PORT));
45         }
46 }

启动测试类,用telnet去连,然后输入各种命令,效果如下:

Mina状态机State Machine_状态机_02

更详细的代码可以参阅: org.apache.mina.example.tapedeck

代码其实都不难,只是我们需要灵活的将状态机这样的模式运用到自己的项目中去,通过状态之间的有规则的切换来控制更复杂的业务逻辑。