DEV Community

jzfrank
jzfrank

Posted on

HFDP(10) - State Pattern

Suppose you are to maintain a gumballMachine, which takes quarters, gives gumball after turning the crank. How would you implement it? The gumball machine certainly behaves differently when in different states (no quarter, inserted one quarter, sold, sold out etc.). Well, we can certainly use if else clauses. However, if new functionalities might be added (for example, randomly generate a winner that gets two gumballs), we can already foresee the code will be messy to maintain.

A natural solution to problem like this, where the object behaves differently under different context, could be the State Pattern.

Formal Definition

The State Pattern allows an object to alter its behavior when its internal state changes. The object will appear to change its class.

We say "appear" because the object cannot change its class after it is initialized. However, it does appears to change its class, as it will behave differently under different context. This is because its state has changed. The way we implement that is to maintain state inside the object, and switch it whenever needed.

State Pattern

Our Context object will have an internal member that maintains State. When request() is called, we are calling state.handle() under the hood. The magic is the State interface. We will have concrete implementation of this interface, and implement handle() differently under different states.

As a side note, we may see similarity between State Pattern and Strategy Pattern. Both of them delegate execution to another composition class (remember our Duck app?). However, the State Pattern is meant for different behaviors of an object under different states. The strategy pattern, in my humber opinion, is like saving us from implementing tons of classes that differ only by a set of behaviors (Don't get me wrong, all of them have the behaviors. They just behave differently).

Top comments (0)