首先,關於狀態機的一個極度確切的描述是它是一個有向圖形,由一組節點和一組相應的轉移函數組成。狀態機經過響應一系列事件而「運行」。每一個事件都在屬於「當前」 節點的轉移函數的控制範圍內,其中函數的範圍是節點的一個子集。函數返回「下一個」(也許是同一個)節點。這些節點中至少有一個必須是終態。當到達終態, 狀態機中止。 css
接下來的問題是,咱們爲何要用狀態機,何時用: java
傳統應用程序的控制流程基本是順序的:遵循事先設定的邏輯,從頭至尾地執行。不多有事件能改變標準執行流程;並且這些事件主要涉及異常狀況。「命令行實用程序」是這種傳統應用程序的典型例子。 程序員
另外一類應用程序由外部發生的事件來驅動——換言之,事件在應用程序以外生成,沒法由應用程序或程序員來控制。具體須要執行的代碼取決於接收到的事件,或者它 相對於其餘事件的抵達時間。因此,控制流程既不能是順序的,也不能是事先設定好的,由於它要依賴於外部事件。事件驅動的GUI應用程序是這種應用程序的典 型例子,它們由命令和選擇(也就是用戶形成的事件)來驅動。 apache
下面咱們看個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. session
狀態機可概括爲4個要素,即現態、條件、動做、次態。 app
下面用代碼來實現這一過程,首先咱們定義動做接口: socket
package com.a2.desktop.example9.mina.statemachine; /** * 動做接口 * * @author ChenHui * */ public interface TapeDeck { void load(String nameOfTape); void eject(); void play(); void pause(); void stop(); }
Tape Deck就是老式的錄音機的意思。而動做接口,就至關於錄音機外面的幾個按鈕。接下來咱們定義狀態: ide
package com.a2.desktop.example9.mina.statemachine; import org.apache.mina.statemachine.annotation.State; import org.apache.mina.statemachine.annotation.Transition; import org.apache.mina.statemachine.annotation.Transitions; /** * 定義狀態 * * @author ChenHui * */ 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.a2.desktop.example9.mina.statemachine; 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這樣的方式咱們用最基本的代碼也能實現出來。接下來咱們要把這樣的方式用在通訊中。用通訊的方式來模擬錄放機的按鈕。
咱們先看狀態的定義:
package com.a2.desktop.example10.mina.statemachine; import static org.apache.mina.statemachine.event.IoHandlerEvents.EXCEPTION_CAUGHT; import static org.apache.mina.statemachine.event.IoHandlerEvents.MESSAGE_RECEIVED; import static org.apache.mina.statemachine.event.IoHandlerEvents.SESSION_OPENED; import org.apache.mina.core.future.IoFutureListener; import org.apache.mina.core.session.IoSession; import org.apache.mina.statemachine.StateControl; import org.apache.mina.statemachine.annotation.IoHandlerTransition; import org.apache.mina.statemachine.annotation.IoHandlerTransitions; import org.apache.mina.statemachine.annotation.State; import org.apache.mina.statemachine.context.AbstractStateContext; import org.apache.mina.statemachine.context.StateContext; import org.apache.mina.statemachine.event.Event; public class TapeDeckServer { @State public static final String ROOT = "Root"; @State(ROOT) // 表示繼承關係 public static final String EMPTY = "Empty"; @State(ROOT) public static final String LOADED = "Loaded"; @State(ROOT) public static final String PLAYING = "Playing"; @State(ROOT) public static final String PAUSED = "Paused"; private final String[] tapes = { "蓋世英雄-王力宏", "惟一-王力宏" }; static class TapeDeckContext extends AbstractStateContext { public String tapeName; } @IoHandlerTransition(on = SESSION_OPENED, in = EMPTY) public void connect(IoSession session) { session.write("+ Greetings from your tape deck!"); } @IoHandlerTransition(on = MESSAGE_RECEIVED, in = EMPTY, next = LOADED) public void loadTape(TapeDeckContext context, IoSession session, LoadCommand cmd) { if (cmd.getTapeNumber() < 1 || cmd.getTapeNumber() > tapes.length) { session.write("- Unknown tape number: " + cmd.getTapeNumber()); StateControl.breakAndGotoNext(EMPTY); } else { context.tapeName = tapes[cmd.getTapeNumber() - 1]; session.write("+ \"" + context.tapeName + "\" loaded"); } } @IoHandlerTransitions({ @IoHandlerTransition(on = MESSAGE_RECEIVED, in = LOADED, next = PLAYING), @IoHandlerTransition(on = MESSAGE_RECEIVED, in = PAUSED, next = PLAYING) }) public void playTape(TapeDeckContext context, IoSession session, PlayCommand cmd) { session.write("+ Playing \"" + context.tapeName + "\""); } @IoHandlerTransition(on = MESSAGE_RECEIVED, in = PLAYING, next = PAUSED) public void pauseTape(TapeDeckContext context, IoSession session, PauseCommand cmd) { session.write("+ \"" + context.tapeName + "\" paused"); } @IoHandlerTransition(on = MESSAGE_RECEIVED, in = PLAYING, next = LOADED) public void stopTape(TapeDeckContext context, IoSession session, StopCommand cmd) { session.write("+ \"" + context.tapeName + "\" stopped"); } @IoHandlerTransition(on = MESSAGE_RECEIVED, in = LOADED, next = EMPTY) public void ejectTape(TapeDeckContext context, IoSession session, EjectCommand cmd) { session.write("+ \"" + context.tapeName + "\" ejected"); context.tapeName = null; } @IoHandlerTransition(on = MESSAGE_RECEIVED, in = ROOT) public void listTapes(IoSession session, ListCommand cmd) { StringBuilder response = new StringBuilder("+ ("); for (int i = 0; i < tapes.length; i++) { response.append(i + 1).append(": "); response.append('"').append(tapes[i]).append('"'); if (i < tapes.length - 1) { response.append(", "); } } response.append(')'); session.write(response); } @IoHandlerTransition(on = MESSAGE_RECEIVED, in = ROOT) public void info(TapeDeckContext context, IoSession session, InfoCommand cmd) { String state = context.getCurrentState().getId().toLowerCase(); if (context.tapeName == null) { session.write("+ Tape deck is " + state + ""); } else { session.write("+ Tape deck is " + state + ". Current tape: \"" + context.tapeName + "\""); } } @IoHandlerTransition(on = MESSAGE_RECEIVED, in = ROOT) public void quit(TapeDeckContext context, IoSession session, QuitCommand cmd) { session.write("+ Bye! Please come back!").addListener(IoFutureListener.CLOSE); } @IoHandlerTransition(on = MESSAGE_RECEIVED, in = ROOT, weight = 10) public void error(Event event, StateContext context, IoSession session, Command cmd) { session.write("- Cannot " + cmd.getName() + " while " + context.getCurrentState().getId().toLowerCase()); } @IoHandlerTransition(on = EXCEPTION_CAUGHT, in = ROOT) public void commandSyntaxError(IoSession session, CommandSyntaxException e) { session.write("- " + e.getMessage()); } @IoHandlerTransition(on = EXCEPTION_CAUGHT, in = ROOT, weight = 10) public void exceptionCaught(IoSession session, Exception e) { e.printStackTrace(); session.close(true); } @IoHandlerTransition(in = ROOT, weight = 100) public void unhandledEvent() { } }
命令的抽象類:
package com.a2.desktop.example10.mina.statemachine; public abstract class Command { public abstract String getName(); }
如下是各種命令,實現形式類似:
package com.a2.desktop.example10.mina.statemachine; public class LoadCommand extends Command { public static final String NAME = "load"; private final int tapeNumber; public LoadCommand(int tapeNumber) { this.tapeNumber = tapeNumber; } public int getTapeNumber() { return tapeNumber; } @Override public String getName() { return NAME; } } package com.a2.desktop.example10.mina.statemachine; public class PlayCommand extends Command { public static final String NAME = "play"; @Override public String getName() { return NAME; } } //如下省略各類命令…
下面是解碼器,繼承了文本的解碼方式:
package com.a2.desktop.example10.mina.statemachine; import java.nio.charset.Charset; import java.util.LinkedList; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.filterchain.IoFilter.NextFilter; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolDecoderOutput; import org.apache.mina.filter.codec.textline.LineDelimiter; import org.apache.mina.filter.codec.textline.TextLineDecoder; public class CommandDecoder extends TextLineDecoder { public CommandDecoder() { super(Charset.forName("UTF8"), LineDelimiter.WINDOWS); } private Object parseCommand(String line) throws CommandSyntaxException { String[] temp = line.split(" +", 2); String cmd = temp[0].toLowerCase(); String arg = temp.length > 1 ? temp[1] : null; if (LoadCommand.NAME.equals(cmd)) { if (arg == null) { throw new CommandSyntaxException("No tape number specified"); } try { return new LoadCommand(Integer.parseInt(arg)); } catch (NumberFormatException nfe) { throw new CommandSyntaxException("Illegal tape number: " + arg); } } else if (PlayCommand.NAME.equals(cmd)) { return new PlayCommand(); } else if (PauseCommand.NAME.equals(cmd)) { return new PauseCommand(); } else if (StopCommand.NAME.equals(cmd)) { return new StopCommand(); } else if (ListCommand.NAME.equals(cmd)) { return new ListCommand(); } else if (EjectCommand.NAME.equals(cmd)) { return new EjectCommand(); } else if (QuitCommand.NAME.equals(cmd)) { return new QuitCommand(); } else if (InfoCommand.NAME.equals(cmd)) { return new InfoCommand(); } throw new CommandSyntaxException("Unknown command: " + cmd); } @Override public void decode(IoSession session, IoBuffer in, final ProtocolDecoderOutput out) throws Exception { final LinkedList<String> lines = new LinkedList<String>(); super.decode(session, in, new ProtocolDecoderOutput() { public void write(Object message) { lines.add((String) message); } public void flush(NextFilter nextFilter, IoSession session) {} }); for (String s: lines) { out.write(parseCommand(s)); } } }
處理異常類:
package com.a2.desktop.example10.mina.statemachine; import org.apache.mina.filter.codec.ProtocolDecoderException; /** * Exception thrown by CommandDecoder when a line cannot be decoded as a Command * object. * */ public class CommandSyntaxException extends ProtocolDecoderException { private final String message; public CommandSyntaxException(String message) { super(message); this.message = message; } @Override public String getMessage() { return message; } }測試類:
package com.a2.desktop.example10.mina.statemachine; import java.net.InetSocketAddress; import org.apache.mina.core.service.IoHandler; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.codec.textline.TextLineEncoder; import org.apache.mina.filter.logging.LoggingFilter; import org.apache.mina.statemachine.StateMachine; import org.apache.mina.statemachine.StateMachineFactory; import org.apache.mina.statemachine.StateMachineProxyBuilder; import org.apache.mina.statemachine.annotation.IoHandlerTransition; import org.apache.mina.statemachine.context.IoSessionStateContextLookup; import org.apache.mina.statemachine.context.StateContext; import org.apache.mina.statemachine.context.StateContextFactory; import org.apache.mina.transport.socket.SocketAcceptor; import org.apache.mina.transport.socket.nio.NioSocketAcceptor; public class TestMain { private static final int PORT = 8082; private static IoHandler createIoHandler() { StateMachine sm = StateMachineFactory.getInstance( IoHandlerTransition.class).create(TapeDeckServer.EMPTY, new TapeDeckServer()); return new StateMachineProxyBuilder().setStateContextLookup( new IoSessionStateContextLookup(new StateContextFactory() { public StateContext create() { return new TapeDeckServer.TapeDeckContext(); } })).create(IoHandler.class, sm); } public static void main(String[] args) throws Exception { SocketAcceptor acceptor = new NioSocketAcceptor(); acceptor.setReuseAddress(true); ProtocolCodecFilter pcf = new ProtocolCodecFilter( new TextLineEncoder(), new CommandDecoder()); acceptor.getFilterChain().addLast("log1", new LoggingFilter("log1")); acceptor.getFilterChain().addLast("codec", pcf); acceptor.getFilterChain().addLast("log2", new LoggingFilter("log2")); acceptor.setHandler(createIoHandler()); acceptor.bind(new InetSocketAddress(PORT)); } }
啓動測試類,用telnet去連,而後輸入各類命令,效果以下:
更詳細的代碼能夠參閱: org.apache.mina.example.tapedeck
代碼其實都不難,只是咱們須要靈活的將狀態機這樣的模式運用到本身的項目中去,經過狀態之間的有規則的切換來控制更復雜的業務邏輯。