ExampleDifficulty: Intermediate1 min

State Example: A TCP Connection

The Gang of Four's own case: open, send and close mean different things when listening, established or closed.

The Gang of Four introduce State with a network connection, and the case shows the pattern in a protocol rather than an application. A TCP connection, the kind a web browser opens to a server, is in one of several states, and each operation does something different in each. This card shows a simplified version of their example as a state diagram and a table, without a listing.

A simplified TCP connection
What each operation does in each state
OperationClosedListeningEstablished
openStarts listeningDoes nothingDoes nothing
sendReports an errorReports an errorSends the data
closeDoes nothingStops listeningSends a close message to the peer

The Gang of Four's design has a TCPConnection context, a TCPState interface with one method per operation, and TCPClosed, TCPListen and TCPEstablished classes. Each row of the table above becomes one method, written once in each class, and each cell is that method's body. The real protocol, defined in RFC 9293, has eleven states; the pattern holds them the same way, with more classes.

One transition here is triggered from outside: the connection becomes established when a peer connects, not when the program calls a method. The context receives that event like any other request and passes it to the current state, so the design does not change.

What this shares with the document example is its shape. In both, the meaning of an operation depends on a current state object, and that object chooses the next one.