State mode (behavioral mode)
Motive (motivation)
In the process of software building, the behavior of some objects changes as they change, such as when the document is read-only, and the behavior of the supported behavior and read-write state may be completely different.
How can I transparently change the behavior of an object at run time based on the state of the object? Without the introduction of tight coupling between object operations and state transitions?
Intentions (Intent)
Allows an object to change its behavior when its internal state changes. This makes the object appear to modify its behavior. --"Design pattern" GoF
Structure (Structure)
Sample code
Public enumdocumentstate {ReadOnly, Editable} Public classDocument {PrivateDocumentstate State; Public voidHandle () {if(state = =documentstate.readonly) {//... } Else if(state = =documentstate.editable) {//... } } }
When documentstate changes, it also causes the document to change, which requires decoupling:
Public Abstract classStateddocument//Abstract Class-represents the behavior of state and dependent state, it is stable { Public Abstract voidHandle1 (); Public Abstract voidHandle2 (); Public Abstract voidHandle3 (); } Public classreadonlystateddocument:stateddocument { Public Override voidHandle1 () {//... } Public Override voidHandle2 () {//... } Public Override voidHandle3 () {//... } } Public classeditablestateddocument:stateddocument { Public Override voidHandle1 () {//... } Public Override voidHandle2 () {//... } Public Override voidHandle3 () {//... } } Public classDocument//Main Logic { Privatestateddocument stateddocument; Public voidsetstateddocument (stateddocument stateddocument) { This. stateddocument =stateddocument; } Public voidHandle1 ()//it does not correspond to a state, but a method that each state will contain{stateddocument.handle1 (); } Public voidHandle2 () {stateddocument.handle2 (); } Public voidHandle3 () {stateddocument.handle2 (); } }
Several points of State mode
- The state mode places all the behaviors related to a particular status in a sub-class object in the state, switches the object when the object is switched, but maintains the interface of the State, thus enabling decoupling between the specific operation and the status transition.
- Introducing different objects for different states makes the state transitions more explicit and guarantees that there will be no state inconsistencies, because the transitions are atomic-either completely converted or not converted.
- If the state object does not have an instance variable, the individual contexts can share the same state object, thereby saving object overhead.
Reprint please specify the source:
Jesselzj
Source: http://jesselzj.cnblogs.com
Design mode 21:state state mode (behavioral mode)