Reprint: http://www.verydemo.com/demo_c92_i259801.html
Object state affects object behavior
Objects have different states and tend to exercise different behaviors...
In the process of software construction, if the state of some objects changes, its behavior will also change. For example, if a document is in a read-only state , the supported behavior may be completely different from the behavior supported by the read-write state . How can I transparently change the behavior of an object at runtime based on its state ? without introducing tight coupling between object operations and state transitions?
Allows an object to change its behavior when its internal state changes. This makes the object appear to modify its behavior.
——《Design Patterns》GoF
If the state of the document is to add a new "print" state , then the enumeration type and the Handle function of the Document class need to be changed. This violates both the Dependency Inversion Principle and the Open Closed Principle.
improved code
Each time the main logic processes a Handle method, the state itself will set the next state , so that the flow of the state is not managed by the main logic itself, but is determined by each state itself, and the state itself determines its own successor. Who. In this way , the state flow and behavior are no longer tightly coupled with the main logic, and there are only runtime dependencies, not compile-time dependencies.
The State mode will be put into a subclass object of State. When the state of the object is switched, the corresponding object will be switched ; but the interface of State will be maintained at the same time, which realizes the decoupling between the specific operation and the state transition. Introduce different objects for different states