State

From HaFrWiki
Revision as of 13:01, 1 April 2015 by Hjmf (talk | contribs) (Created page with "{{TOCright}} == Difference between State and Strategy == Patterns State and Strategy seems closely related. Therefor some rules of thumb to decide which pattern to use: # The...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Difference between State and Strategy

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

top

Reference

top