当我们在开发复杂的网络应用的时候往往需要一个状态的设计,下面就以官网的一个收录机播放为例来说明:
收录机状态之间的转换我们应该不难理解:首先是空状态,就是什么磁带就没放进去然后是有磁带的状态,这两个状态之间的转换就是通过eject方法和load方法来交互的,
loaded表示已经有磁带了,那么我们发出play指令,这时候收录机就会播放磁带,这就是一个新状态playing,当我们点击stop时,状态又从playing转换为loaded了,当状态为playing的时候,点击pause按钮就会停止播放,再点击播放按钮就会继续播放,所以总结起来就是4种状态:Empty、Loaded、Playing、Paused,5个方法:eject,loaded,stop,play、pause。
下面我们在一个接口中定义这几个方法:
然后用字符串常量定义这几种状态,并且用注解将方法、状态和会执行的方法进行关联:public interface TapeDeck { void load(String nameOfTape); void eject(); void play(); void pause(); void stop(); }
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";
//当执行load方法 从empty状态转换到loaded状态时执行的方法
@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(on = "load", in = EMPTY, next = LOADED)
public void loadTape(String nameOfTape)
它的意思就是说当收录机从Empty状态,执行了load方法时loadtype方法将会被调用,然后收录机的状态会变为loaded。
下面是测试代码:
public static void main(String[] args) { TapeDeckHandler handler = new TapeDeckHandler();//自定义的状态和方法 StateMachine sm = StateMachineFactory.getInstance(Transition.class). create(TapeDeckHandler.EMPTY, handler);//用工厂方法基于 Transition注解创建一个状态机,初始状态为Empty,处理方法基于自定义的类 TapeDeck deck = new StateMachineProxyBuilder().create(TapeDeck.class, sm); //创建一个状态机代理对象,代理上一步产生的状态机 deck.load("The Knife - Silent Shout"); deck.play(); deck.pause(); deck.play(); deck.stop(); deck.eject();}
运行结果如下:
Tape 'The Knife - Silent Shout' loaded
Playing tape
Tape paused
Playing tape
Tape stopped
Tape ejected