Summary: in this tutorial, you will learn how to use the state design pattern.
Problem
Normally the behaviors of an object depend on its states. To change the behavior of the object, you need to use a lengthy if
or case
statements. In addition, when you add a new state to the object, the logic for those methods has to change accordingly, which is quite time-consuming.
Suppose that you have a Request
object that can be any request such as travel request, leave request, etc.
The Request
object has different states:
- Planning
- Submitted
- Approved
- Rejected
The Request
object also has different behaviors such as:
- Save
- Submit
- Approve
- Reject
- Activate
You can only approve or reject a request when its status is submitted. And you can only activate a request when its state is approved. The behavior of Request object changes based on its current state.
The following shows how to implement the zcl_request
class:
CLASS zcl_request IMPLEMENTATION.
METHOD save.
CASE mv_status.
WHEN 'PLANNING'.
" logic for saving request here
WHEN 'SUBMITTED'.
WHEN 'APPROVED'.
WHEN 'REJECTED'.
WHEN 'ACTIVATE'.
" raise an exception for invalid operations here.
ENDCASE.
ENDMETHOD.
ENDCLASS.
And you have to write other methods such as submit, approve, reject, activate, and revise in the same way.
How do you make it cleaner? The state design pattern is the answer.
Intent
The state design pattern allows an object to change its behavior when its internal states changes. The object will appear to change its class.
State Design Pattern UML Diagram
The classes and/or objects are participating in the state design pattern are:
- Context (Request)
- Provide the interface for the external object that uses this object.
- Maintain an instance of ConcreteState which defines the current object’s state.
- State (in planning, submitted, approved, rejected, active)
- Provide an interface that encapsulates all behaviors associated with a particular state of the Context.
- ConcreteState
- Implement all behaviors associated with a particular state of the Context
State Design Pattern Implementation
We will encapsulate the state of the request object in classes and add a number of subclasses corresponding to the states of the Request object.
The following UML diagram illustrates the state design pattern: