Status mode: state
definition : When an object's internal state changes, allowing changes to its behavior, the object looks like it has changed its class.
Example:
Design pattern in the book, the example of TCP state transfer is given. For example, when a TCP connection receives a SYN in the Listen state and sends Syn+ack, it enters the SYN receive state. When an ACK is received in the SYN receive state, it enters the established state, and in a normal program, a large number of if else or switch are required to determine the command received and the corresponding state changes.
Such as:
if (stat = = listen)
if (Receive SYN and send Syn,ack)
Stat = established
else ...
State mode primarily addresses this type of problem. When the conditional expression that controls an object state transition is too complex,
Transfer the judgment logic of state transitions to a series of classes that represent different states. Complex logic can be simplified.
Class diagram for State mode:
State class: An abstract status class that defines the behavior that an interface uses to encapsulate the specific state of a context class.
Concertstate: A specific state class in which each subclass implements the behavior associated with the context state.
Context: Maintains an instance of the State class that represents the current status.
The TPC State Transfer program can be designed as follows:
1 classTcpconn2 {3 Public:4 tcpconn ();5 voidListen () {_stat->listen ( This);6 voidsynreceived ();7 ......8 voidSetState (tcpstat* state) {_state =State ;}9 Private:Tentcpstate*_state; One }; A - classtcpstate - { the piblic: -VirtaulvoidChangestae (Tcpconn *conn); -VirtaulvoidListen (tcpconn*conn); -VirtaulvoidSynreceived (tcpconn*conn); + }; - + classTcplistenstate: Publictcpstate A { at Virtual voidListen (tcpconn*conn) - { - //receive Ayn send ack and SYN -Conn.setstate (Newtcpsynreceivedstate ()); - } - } in - to Client: +tcpconn* conn =NewTcpconn; -Conn->listen ();
Consider using state mode when the behavior of an object depends on its state, and it must change its behavior based on the state.
State mode of design mode