Course contentsShow
← Software Engineering
Lesson 309 of 1,9339. Behavioral Design PatternsFree lesson

State Pattern Structure: Context and State Objects

Learning the Context class, State interface, and ConcreteState classes that encapsulate state-specific behavior.

State Pattern Structure: Context and State Objects

You'll learn how the State pattern organizes state-specific behavior across three key components: the Context, the State interface, and ConcreteState classes.

The Core Components

The State pattern divides responsibilities into three distinct roles:

The Context is the object whose behavior changes based on its internal state. It maintains a reference to a current State object and delegates state-specific requests to it. Think of the Context as a character in a video game—its actions depend on whether it's running, jumping, or crouching.

The State interface defines the contract that all concrete states must follow. It declares methods for operations that vary depending on the current state. Each method typically corresponds to a behavior that changes based on context.

ConcreteState classes implement the State interface, each encapsulating the behavior for one specific state. When the Context is in a particular state, it uses the corresponding ConcreteState object to handle requests. A door might have OpenState and ClosedState classes, each defining what happens when you try to open, close, or lock the door.

How They Work Together

The Context doesn't contain large conditional statements checking its state. Instead, it simply delegates to its current State object. When state transitions occur, the Context (or sometimes the State itself) switches to a different ConcreteState object.

For example, a TCPConnection context might hold a reference to states like Listening, Established, or Closed. When data arrives, the Context asks its current state object to handle it—the Established state processes the data, while Closed might ignore it.

Key Takeaway: The State pattern uses three components—Context (holds current state), State interface (defines state behavior contract), and ConcreteState classes (implement specific state behaviors)—to eliminate complex conditionals and make state transitions explicit.