java 状态机编程,如何在java中创建一个简单的状态机

I am currently learning java and would like to know how to control state in a OO way. I implemented a Pong app. If I wanted multiple states like gameplay and menu, and each one of these states had to execute start, stop and run how would I achieve this and how would I switch between these states.

I know I could simply throw in a big switch statement but what's the best way to implement this?

I want to be able to switch to the menu state in the gameplay state and vice versa.

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

public class Pong extends Applet implements Runnable, KeyListener{

public void start ()

{

setSize(screen);

setFocusable(true);

Thread th = new Thread (this);

th.start ();

}

public void stop()

{

}

//Etc..

}

解决方案

You can simulate a basic FSM (Finite State Machine) using enums:

public enum State {

ONE {

@Override

public Set possibleFollowUps() {

return EnumSet.of(TWO, THREE);

}

},

TWO {

@Override

public Set possibleFollowUps() {

return EnumSet.of(THREE);

}

},

THREE // final state

;

public Set possibleFollowUps() {

return EnumSet.noneOf(State.class);

}

}

While the code to generate this will be very verbose if things get more complicated, the nice part is that you get compile-time safety, thread-safety and high performance.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值