Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a simple state machine in 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..
}
like image 751
Sam152 Avatar asked Apr 26 '11 12:04

Sam152


People also ask

What is a state machine in Java?

A state machine — also called a finite state machine or finite automaton — is a computational model used to build an abstract machine. These machines can only be in one state at a given time. Each state is a status of the system that changes to another state. These state changes are called transitions.


1 Answers

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

public enum State {

    ONE {
        @Override
        public Set<State> possibleFollowUps() {
            return EnumSet.of(TWO, THREE);
        }
    },

    TWO {
        @Override
        public Set<State> possibleFollowUps() {
            return EnumSet.of(THREE);
        }
    },

    THREE // final state 

    ;
    public Set<State> 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.

like image 131
Sean Patrick Floyd Avatar answered Sep 22 '22 13:09

Sean Patrick Floyd