Changing object behavior with the state pattern
The behavior state pattern defines the procedure for influencing an object’s internal processes based on the mutation of its internal state. This pattern is part of the GoF’s book.
Motivation
Object states can be thought of as representing the concept of a finite machine. A pattern allows an object to change its behavior when its internal state changes. The state pattern enforces that an object describes its internal states with specific classes, and maps responses to those states to specific instances.
Finding it in the JDK
Usage of the state pattern can be found in the implementation of the jlink
plugin, the jdk.jlink
module, and the jdk.tools.jlink.plugin
package. The interface plugin defines a nested enum class, State
, whose values are references to the states in question.
Sample code
The next example considers that each vehicle has different states that are well identified (Example 5.20):
public...