State Pattern Tutorial
This tutorial is aimed to guide the definition and application of Gang of Four (GoF) state design pattern. By reading this tutorial, you will know how to develop a model for the state pattern, and how to apply it in practice.
Modeling a Design Pattern with a Class Diagram
- Create a new project named Design Patterns.
- Create a class diagram named State.

- Select Class from the diagram toolbar. Click on the diagram to create a class and name it Context.

- Right-click on the Context class and select Add > Operation from the popup menu.

- Name the operation `Request()`.

- Move the mouse cursor over the Context class and drag out Aggregation > Class to create an associated class named State.

- Right-click on State and select Model Element Properties > Abstract to set it as abstract.

- Right-click on the State class and select Add > Operation from the popup menu.

- Name the operation `Handle()`.

- Right-click on the Handle() operation and select Model Element Properties > Abstract to set it as abstract.

- Move the mouse cursor over the State class and drag out Generalization > Class to create a subclass named ConcreteState.

- We need to make the concrete state inherit operations from the state class. Right-click on ConcreteState and select Related Elements > Realize all Interfaces from the popup menu.

- In practice, there may be multiple concrete states. To represent this, stereotype the `ConcreteState` class as PTN Cloneable. Right-click on ConcreteState and select Stereotypes > Stereotypes... from the popup menu.

- In the Stereotypes tab of the Class Specification dialog box, select PTN Cloneable and click > to assign it to the ConcreteState class. Click OK to confirm.

Defining the Pattern
- Select all classes on the class diagram.

- Right-click on the selection and select Define Design Pattern... from the popup menu.

- In the Define Design Pattern dialog box, specify the pattern name as State. Keep the file name as is. Click OK to proceed.

Applying a Design Pattern to a Class Diagram
In this section, we are going to apply the state pattern in modeling a 'Life' concept.
- Create a new project named Life.
- Create a class diagram named Domain Model.
- Right-click on the class diagram and select Utilities > Apply Design Pattern... from the popup menu.

- In the Design Pattern dialog box, select State from the list of patterns.

- In the bottom pane, rename Context, State, and ConcreteState to Life, LifeState, and IdleState, respectively.

- We need two more concrete states for 'up' and 'down'. Click the + button in the `ConcreteState` row and select Clone... from the popup menu.

- Enter `2` as the number of classes to clone and click OK to confirm.

- Rename ConcreteState2 and ConcreteState3 to UpState and DownState.

- Click OK to apply the pattern to the diagram.
- Tidy up the diagram. Here is the result:
