Applied Design Patterns with Java

Behavioral :: State (305) {C ch 23}


Example - Java :: Patterns\Behavioral\State

Pattern Concept: to allow an object to alter its behavior when its internal state changes. The object will appear to change its class. Operationally, the State pattern makes an object represent the state of an application; application state representation changes can occur by simply switching to another object. An enclosing class might switch between a number of related classes and pass method calls on to the current contained class. The State pattern is intended to replace cumbersome switch ... case statements.

Cooper's example builds on the simple drawing programs elaborated in the Memento and Mediator chapters. The following illustration shows the drawing program's basic interactions:

The Mediator is the de facto state manager, which is not its actual purpose; in this architecture, it becomes too complex and large. A State object, from a class hierarchy, is needed to manage object states:

public class State {

public void mouseDown(int x, int y) { ... }

public void mouseUp(int x, int y) { ... }

public void mouseDrag(int x, int y) { ... }

public void select(Drawing d, Color c) { ... }

}

public class RectState extends State {

private Mediator med;

...

}

public class StateManager {

private State currentState;

private RectState rstate;

...

}

The StateManager class sets the current state and executes methods on the State object; a typical State object can override those event methods that require special handling. Here is the illustration:



Example - UML : StateDraw
The example uses a Mediator to switch between states, and to forward the command requests to the specific objects. Here are Cooper's Class Diagrams for the application using this logic, followed by the Rose equivalent, which also shows the Memento object to capture and process Undo operations:





The example Java program is called 'StateDraw'.

The UML diagram is above, and the list of Java files is below:

Issues and consequences of the State pattern include:

Catalog Behavioral Prev Next