To write a State machine.

M

maadhuu

Can someone tell me the best way to go about writing a state machine in
Java ?

Thank you
maadhuu
 
R

Robert Klemme

maadhuu said:
Can someone tell me the best way to go about writing a state machine in
Java ?

This smells like a homework assignment... Here's a start

public class StateMachine {
}

Cheers

robert
 
G

Gordon Beaton

Can someone tell me the best way to go about writing a state machine in
Java ?

Sounds like homework, but here's the general idea (no code):

- define a set of classes representing the states, each with a similar
transition method that receives an event, processes it and returns
the next state.

- define a class representing the state machine, with a method that
receives events, invokes the transition method of the current state,
then changes state accordingly.

/gordon
 
R

rapp

maadhuu said:
Can someone tell me the best way to go about writing a state machine in
Java ?

Thank you
maadhuu

If depends on the state machine's complexity. If you have a simple
state machine of ~6 states and few transitions, then use an enum to
list the states, a class member to store the current state and switch
statements based on the current state to decide how to respond to an
event based on the current state.

I use this solution when I have a simple "connecting, connected,
disconnecting, disconnected" FSM and transitions between states are
straight forward.

But as the number of states and transitions grow, this mechanism
becomes difficult to correctly implement. The switch statements are
scattered throughout your event processing code. Adding a new state or
transition requires touching all these switch statements.

The State Pattern is one solution to this problem. Each state is a
class and each transition is a state class' method. So all the FSM code
is collected into these states. The downside is writing code for those
state classes and transition methods. The solution to that problem is
to define your FSM in a separate file and use another program to
generate the State Pattern code for you based on your FSM definition.

The open source application SMC does just that. It allows you to define
complex state machines and SMC generates the State Pattern code in
several different languages - including Java. You learn about SMC at
http://smc.sourceforge.net. The site contains both a Programmer's
Manual and a FAQ.

Charles Rapp
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top