State

From HaFrWiki
Jump to: navigation, search

Difference between State and Strategy[edit]

Patterns State and Strategy seems closely related. Therefor some rules of thumb to decide which pattern to use:

  1. The difference simply lies in that they solve different problems:
  • The State pattern deals with what (state or type) an object is (in) -- it encapsulates state-dependent behavior.
  • The Strategy pattern deals with how an object performs a certain task -- it encapsulates an algorithm.

The constructs for achieving these different goals are however very similar; both patterns are examples of composition with delegation.


The Strategy pattern is really about having a different implementation that accomplishes (basically) the same thing, so that one implementation can replace the other as the strategy requires. For example, you might have different sorting algorithms in a strategy pattern. The callers to the object does not change based on which strategy is being employed, but regardless of strategy the goal is the same (sort the collection).

The State pattern is about doing different things based on the state, while leaving the caller relieved from the burden of accommodating every possible state. So for example you might have a getStatus() method that will return different statuses based on the state of the object, but the caller of the method doesn't have to be coded differently to account for each potential state.


See also[edit]

top

Reference[edit]

top