State pattern – A logical ‘Finite State Machine’ State - Design Pattern State pattern – A logical ‘Finite State Machine’
Introduction State pattern Intent For an abstraction that executes a finite state machine Intent To allow an object to alter its behavior when its internal state changes. The object appears to have changed its class
Details Implementing objects states using explicit classes Examples TCP_Connection Established, Listen, Closed Car_PowerBand In Powerband, Below PowerBand and Above PowerBand Implementing the state concept Constant identifiers and Conditional logic Define different State class for each logical state
Implementing the State pattern From the object collaboration angle Context object and the State object Context object An object going through the different states Context maintains an object reference to the state State All different states are ‘concrete classes’ inheriting from an ‘abstract state base class’ State classes implement the ‘handle()’ method which localizes actions to be taken on an event in the FSM
Details Working the State Pattern Benefits of the State pattern Client configures Context with initial state States take care of state transition and state specific actions to be performed Benefits of the State pattern Localization of State specific behavior Partition behavior for different states
The Car Example
Writing a generic State class abstract class State { static State initialState; static final State state1 = new State1(); static final State state2 = new State2(); protected State() { if (initialState == null) initialState = this; } abstract void stateExit(StateOwner owner); abstract void stateEnter(StateOwner owner); }
Writing a generic State class class State1 extends State { void stateExit(StateOwner owner) { } void stateEnter(StateOwner owner) { } } class State2 extends State { void stateExit(StateOwner owner) { } void stateEnter(StateOwner owner) { } }
Conclusion State pattern For an abstraction that executes a finite state machine Relies heavily on the OO concept of dynamic binding / Abstract base classes