2006.9.11 Li Jianzhong
Object status affects object behavior
Objects have different states and often perform different behaviors ......
Motivation)
In the process of software building, if the status of some objects changes, their behavior also changes. For example, if a document is in the read-only status, the supported behaviors and read/write statuses may be completely different.
How can I transparently change the behavior of an object based on the object state at runtime? Does it introduce tight coupling between object operations and state conversion?
Intent)
Allows an object to change its behavior when its internal state changes. So that the object seems to have modified its behavior.
-- Design Pattern GoF
For example, State mode Application
If you want to add a new "print" state to the Document state, you need to change the Handle function of the enumeration type and Document class. This violates both the Dependency inversion principle and the open and closed principle.
Improved code
Each time a Handle method is processed by the main logic, the State itself sets the next state, so that the State flow is not managed by the main logic itself, but determined by each State, the status determines who the successor is. In this way, the status flow and behavior are no longer tightly coupled with the main logic. Only the dependency at runtime is involved, but the dependency at compilation is not.
Structure)
Key Points of State Mode
In State modeAll actions related to a specific statusAll are placed in a State subclass object. When the object State is switched, the corresponding object is switched. But the interface that maintains the State is also implemented, which decouples the specific operation from the State conversion.
Introducing different objects for different States makes the State Transition clearer, and it can be ensured that there will be no State inconsistency, because the transition is atomic-that is, either it is completely converted, or do not convert.
If the State object does not have instance variables, the context can share the same State object, saving the object overhead.
2010.10.25