Java Demo for finite state machine (FSM)

Source: Internet
Author: User

In this paper, we start from a simple example, and gradually evolve into a very complex program.

In the condensed state mode (5.8), transitions between states are controlled by the outside world, or. A variety of States are cut and irrelevant. The most interesting part of state mode is the evolution of its state.

1. Intro

The remote control of the air conditioner (air-condition) has two buttons(many other buttons are introduced in the following example),power/the Power key and the cool/refrigeration key .

Air conditioning is performed in 3 states. Stop/off, only send wind/fanonly, refrigeration/cool. the starting state is off, and the status change diagram is seen below.

This is a simplified finite state machine (finite, FSM, or finite state automata) graph that uses 3 elements of the status graph: ① bubbles, which represent state. An arrow representing the ② connection state represents the transformation (transition). ③ the flag on the arrow is an event.


The transition of the state, look at the picture to speak. Press the Power key to Off→fanonly, Cool→off, and so on. According to cool, then Off→off (no painting, like a full point on their own drawing it).

For such a simple state conversion, yqj2065 still likes branching statements . , concise and crisp.

Routine 4-5 simple and crisp package property.state.statemachine;import static tool. print.*;//pln/** * Air Conditioning aircon. Simple model: * The remote has two buttons (many other buttons are introduced in the following example), the power supply key and the cool refrigeration key. * Air conditioning is performed in 3 states. Stop/off, only send wind/fanonly, refrigeration/cool. * Start status is off * @author (yqj2065) * @version 0.1 */public class aircon0{//Off,fanonly.    AC private int state=0;//Start status is off public int getState () {return state;}            Two action public void power () {//Press Power key if (state==0) {//off state=1;         PLN ("Start Fan");            }else if (state==1) {//fanonly state=0;         PLN ("Stop Fan");            }else{state=0;         PLN ("Stop Cool");        }} public void Cool () {//press the refrigeration key if (state==0) {//off PLN ("nothing");            }else if (state==1) {//fanonly state=2;         PLN ("Start Cool");            }else{state=1;         PLN ("Stop Cool"); }}}package property.state.statemachine;public class acctrl{public static void Test () {Aircon0 Ac = new Aircon0 ();//power () Cool () System.out.println ("Current state:" + ac.getstate ());        Ac.cool ();        Ac.power ();        Ac.cool ();        Ac.cool ();        Ac.power ();    Ac.power (); }}
The output of the test code:

Current state:0
Nothing
Start Fan
Start Cool
Stop Cool
Stop Fan
Start Fan

On this basis, you can spend 10 minutes practicing, using the state mode to change the above code.

we use enum Write the status class hierarchy. Its structure is as follows:

Routine 4 6 enum Stateenum state0{    off{        @Override void Power () {                    }        @Override void Power () {        }    }, fanonly{    },    cool{};    public abstract void power ();    public abstract void Cool ();

(State1 should be used as the inner class of Aircon1.) On the Outside, power () and so on need to join the number of Aircon1, into power (Aircon1 AC)).

Now. Enrich the details of the finite state machine and add ④ action (action), such as events, corresponding actions and state actions.


For this reason, in enum State1, in addition to the state pattern extraction interface. Added various actions of state machine/action Methode
void entry (Aircon1 ac) {PLN ("→" +ac.state.name ());}
void exit (Aircon1 ac) {p (ac.state.name () + "→");}
void Startcool () {p ("Start Cool"); }
void Stopcool () {p ("Stop Cool"); }
void Startfan () {p ("Start Fan"); }
void Stopfan () {p ("Stop Fan"); }

Each power (Aircon1 ac), Cool (Aircon1 ac) method body structure is:

This.exit (AC);
Suppose there is. Events (event) corresponding to the action, such as Stopfan ();
Ac.state =off; Next state
Ac.state.entry (AC);

Package Property.state.statemachine;import static tool. print.*;//pln/** * should have State1 as the inner class of Aircon1. And now it's outside. * Power () required to become power (Aircon1 ac) */public enum state1{off{@Override void exit (Aircon1 ac) {super.exit (AC); startf        An ();}            @Override void Power (Aircon1 ac) {this.exit (AC);                        Ac.state =fanonly;         Ac.state.entry (AC);        } @Override void Cool (Aircon1 ac) {PLN ("nothing");            }},fanonly{@Override void power (Aircon1 ac) {this.exit (AC);            Stopfan ();            Ac.state =off;         Ac.state.entry (AC);            } @Override void Cool (Aircon1 ac) {this.exit (AC);            Ac.state =cool;        Ac.state.entry (AC);        }}, cool{@Override void exit (Aircon1 ac) {super.exit (AC); Stopcool ();}        @Override void entry (Aircon1 ac) {startcool (); Super.entry (AC);}   @Override void Power (Aircon1 ac) {this.exit (AC);         Stopfan ();            Ac.state =off;         Ac.state.entry (AC);            } @Override void Cool (Aircon1 ac) {this.exit (AC);            Ac.state =fanonly;          Ac.state.entry (AC);    }    };    Interface for State mode extraction abstract void power (Aircon1 ac);    abstract void Cool (Aircon1 ac);    The various actions of the state machine action Methode void entry (Aircon1 ac) {PLN ("→" +ac.state.name ());}    void exit (Aircon1 ac) {p (ac.state.name () + "→");}    void Startcool () {p ("Start Cool");    } void Stopcool () {p ("Stop Cool");    } void Startfan () {p ("Start Fan");    } void Stopfan () {p ("Stop Fan"); }    }

Change version number of air conditioner Aircon1.

Package Property.state.statemachine;import static tool. print.*;//pln/** * Air Conditioning Aircon1. Use state mode to refactor Aircon0. Use the enum State1 to write the state class hierarchy.

* @author (yqj2065) * @version 0.1 */public class aircon1{ State1 state= state1.off;//private changed to default. Delete GetState (). //Two action public Void Power () {//Press Power key State.power (this); } public void Cool () {//press refrigeration key State.cool (this); } /** * Acctrl code.

* /public static void Test () { Aircon1 ac = new Aircon1 (); System.out.println ("Current state:" + ac.state.name ()); Ac.cool (); Ac.power (); Ac.cool (); Ac.cool (); Ac.power (); Ac.power (); Ac.power (); }}

The output of the corresponding test operation: "off→" means leaving the off state, while "→fanonly" ...

Current State:off
Nothing
Off→start fan→fanonly
Fanonly→start Cool→cool
Cool→stop cool→fanonly
Fanonly→stop Fan→off
Off→start fan→fanonly
Fanonly→stop Fan→off

2. Layered state machine for state machine with more states. It is common to combine states with many common attributes. Like Fanonly and cool.Running Status。


The hierarchical States in the state machine, we can use the combination mode processing. (There is no separate write combination mode,).

However, it is not always possible to use the combination mode perfectly. For example running to off, the internal state of all running is converted to off at Poverevent. Very good; off to running. Not all running internal states have to call their entry. Use the chain of responsibility when using enum (not a class level).



The landlord drawing, consider many other buttons ....


Java Demo for finite state machine (FSM)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.