System Design  «Prev  Next»
Lesson 5 State design pattern
ObjectiveExplain how to map the statechart to the state design pattern.

State Design Pattern

Managing state-specific behavior

When an object exhibits a lot of state-specific behavior the code can become large, complex, and difficult to follow. For each behavior that the object can manifest, the implementation may be different for each state of the object. For example, a relatively simple object with six states and six behaviors would require 36 blocks of implementation code, one block of code for each behavior for each state.
View the image below to see an example of this.
State Code

State Design Pattern

State Pattern One technique for coping with the complexity of state-specific behavior is the state design pattern. This pattern uses the concept of delegation to separate the implementation of a behavior from the object that is responsible for the behavior.
For example, most of us are responsible for filing taxes. However, for some of us, the process is extremely complex and requires assistance from an expert. We retain ultimate responsibility for filing the taxes, but we delegate the actual process to a specialist who does it for us. When the tax specialist is finished, he/she returns the results to us. Click the View Image button to see the key components of the state design pattern.

State Design Pattern

When an object's behaviors differ depending on the object's state, you can define new objects that represent the object's state. Each unique state object type has its own implementation for each behavior. When the object needs a behavior it "delegates" the behavior to the appropriate state object. Once the behavior has been completed, the state object returns control to the original object.
Let us look at a Java example:
void SubmitClaim(Claim) { 
  state.SubmitClaim(Claim) 
}

Note how the operation simply invokes another operation of the same name on the object referred to by the state attribute. The interface does not really even have an implementation of its own.

Map the state diagram to the state pattern

The statechart diagram provides an explicit description of the states of an object. To create the state pattern in your class diagram click the View Image button and follow the steps.
State Design Pattern
The state pattern is not appropriate for every application of state-specific behavior. However, when you are faced with increasing numbers of states and a variety of behaviors, the pattern can pay huge dividends in ease of maintenance and understandability.