The state of an object is composed of the current values of each property. When we call an object's Setxxx () method, it usually means modifying its XXX property. In addition, an object may modify its own state when it executes a method. In some cases, such as the creation of a transaction or machine model, the state of the object may be a key factor in determining its behavior, and the state-dependent code logic may be pervasive in a large number of methods of the class. The goal of the state pattern is to simplify this type of code by concentrating the logic of States on a set of classes, each representing a different state, avoiding if statements being nested too deep or too complex, and instead relying on polymorphism to invoke different methods.
State model
If the object's state information is critical, the object will have some variables that indicate how to make the appropriate action based on the state. These variables are heavily dispersed in complex, multi-layered nested IF statements to describe how an object responds to events that might occur. The biggest drawback to building an object model in this way is that if statements can become quite complex. Once you modify the state model of an object, many if statements for multiple methods often need to be adjusted.
Taking the door of the conveyor as an example, consider the state change process: the door of the conveyor belt is controlled by a single button and is assumed to be in a closed state at the initial time. Click the button door to start opening, and if the button is pressed again before the door is completely open, the door starts to close. Once the door is fully open, it will automatically start the shutdown process after a 2-second delay. To prevent the door from automatically closing, you can click the button after the door is opened. Fig. 1 describes the state change of the portal. It is a UML state Machine, where click indicates the action of pressing the button. Obviously, the UML state machine diagram is more intuitive and understandable than the plain text description.
According to the conventional design idea (no State design pattern), a Door1 object can be used to represent the portal (as shown in Figure 2) in software that simulates the conveyor's working process, and the status change event is sent to the Door1 object by the conveyor software.
Figure 1 UML State machine
Figure 2 State Change event sent to Door1 object