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

The State Pattern: Definition and Intent

Understanding how State pattern allows objects to alter behavior when internal state changes.

The State Pattern: Definition and Intent

What you'll learn: How the State pattern enables an object to change its behavior dynamically when its internal state changes.

The Core Problem

Imagine a simple vending machine. When it has no coins inserted, pressing the dispense button does nothing. But after inserting coins, that same button now dispenses a product. The machine's behavior changes based on its current state—yet you're pressing the same button!

In code, you could handle this with a giant if-else or switch statement checking the current state before every operation. But this approach becomes unmaintainable as states and transitions multiply. The State pattern offers a cleaner solution.

What is the State Pattern?

The State pattern allows an object to alter its behavior when its internal state changes. It appears as if the object changed its class—because different state objects handle the same request differently.

Instead of the object containing conditional logic for every state, each state becomes its own class. The main object (the context) delegates behavior to the current state object. When the state changes, the context simply switches which state object it's using.

The Intent

The State pattern's intent is to:

  • Eliminate complex conditional logic based on state
  • Localize state-specific behavior into separate classes
  • Make state transitions explicit and manageable
  • Allow adding new states without modifying existing code

Think of it like a light switch: the switch itself doesn't contain all the logic for "on" and "off" states. Instead, it delegates to its current state, and flipping the switch just changes which state is active.

Key Takeaway: The State pattern encapsulates varying behavior for the same operations based on an object's internal state, replacing conditional logic with polymorphism and making state management explicit and extensible.