Applied Design Patterns with Java

Behavioral :: State (305) {C ch 23}

Intent
Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.

As Known As
Objects for States

Motivation
Consider a class TCPConnection that represents a network connection. A TCPConnection object can be in one of several different states: Established, Listening, Closed. When a TCPConnection object receives requests from other objects, it responds differently depending on its current state. For example, the effect of an Open request depends on whether the connection is in its Closed state or its Established state. The State pattern describes how TCPConnection can exhibit different behavior in each state. The key idea in this pattern is to introduce an abstract class called TCPState to represent the States of the network connection. The TCPState class declares an interface common to all classes that represent different operational states. Subclasses of TCPState implement state-specific behavior. The classes TCPEstablished and TCPClosed implement behavior particular to the Established and Closed states of TCPConnection.

The class TCPConnection maintains a State object (an instance of a subclass of TCPState) that represents the current state of the TCP connection. The class TCPConnection delegates all state-specific requests to this State object. TCPConnection uses its TCPState subclass instance to perform operations particular to the state of the connection. Whenever the connection changes state, the TCPConnection object changes theState object it uses. When the connection goes from established to closed, TCPConnection will replace its TCPEstablished instance with a TCPClosed instance.

Catalog Behavioral Prev Next