Saturday, December 27, 2014

State Pattern

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

This design pattern should be considered when the application needs to maintain certain state machine.

The State Pattern suggests that:
  1. Encapsulate each state into a separate class.
  2. The Context delegates to the current state to handle requests.
  3. Once a request is handled, the current state may change.
Design Principles follows:
  1. Encapsulate what varies.
  2. Favor composition over inheritance.
  3. Open-Closed principle: closed for modification but open for extension.
State and Strategy patterns are similar in structure, but what they intent to do is quite different.

In case of Strategy Pattern, objects stick to one particular kind of a behavior.

In case of State Pattern, objects change state over time according to some well defined state transitions.

Vending machine implementation is a very good application of a State Pattern.

No comments:

Post a Comment