Strategy

From CSSEMediaWiki
Revision as of 03:06, 20 August 2008 by Dominic Winkler (Talk | contribs)
Jump to: navigation, search

Contents

Intent

"Define a family of algorithms, encapsulate each one, and make them interchangeable" [GoF] That means to capture the abstraction in an interface and bury implementation in derived class, so that it lets the algorithm vary independently from clients that use it depending on the context.

When to use it

The strategy pattern is useful for situations where

  • it is necessary to dynamically swap the algorithms used in an application
  • many related classes just differ in their behavior
  • data within an algorithm is meant to be hidden from the context/client

UML Diagram

Strategy.jpg

Example

An Example would be a tax program, where you have different methods of calculating the taxrates depending on the country.

Strategy vs State

The State pattern in terms of design is quite similar to the Strategy pattern, but they differ in the way they are used. While in the derived classes of the strategy pattern most of the times just one different algorithm is implemented, the derived classes of the state pattern usually represent an independent state of something. That means they have their own fields, methods and so on.

Personal tools