Modeling Design Pattern with Class Diagram
- Create a new project Design Patterns.
- Create a class diagram State.
- Select Class from diagram toolbar. Click on the diagram to create a class. Name it as 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 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 Handle, 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 subclasses ConcreteState.
- We need to make the concrete states 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 class ConcreteState 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 ConcreteState class. Click OK to confirm.
Defining 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 State. Keep the file name as is. Click OK to proceed.
Applying Design Pattern on Class Diagram
In this section, we are going to apply the state pattern in modeling a life.
- Create a new project Life.
- Create a class diagram 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.
- At the bottom pane, rename Context, State and ConcreteState to Life, LifeState and IdleState.
- We need 2 more concrete states for up and down. Click on the + button at the ConcreteState row and select Clone... from the popup menu.
- Enter 2 to be the number of classes to clone. Click OK to confirm.
- Rename ConcreteState2 and ConcreteState3 to UpState and DownState.
- Click OK to apply the pattern to diagram.
- Tidy up the diagram. Here is result: