Monday, December 11, 2006

The Strategy Pattern

The strategy pattern is intended to provide a means to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. It is useful for situations where it is necessary to dynamically swap the algorithms used in an application. In Design Patterns, the authors define the Command pattern as:
Define a family of algorithms, encapsulate each one, and make them interchangeable.
Strategy lets the algorithm vary independently from clients that use it.
The Strategy pattern consists of a family of related algorithms behind a driver class called the Context. Either the client or the context select the which one of the algorithms to use for the given situation. The strategy pattern may be used in the following scenarios:
  • When you have many related classes that differ only in behavior. Strategy pattern provides a way to configure a class with one of many behaviors.
  • Strategy pattern can be used when you have different variants of an algorithm. Each variant can be encapsulated within a strategy.
  • An algorithm uses internal data structures that need not be exposed to the client.
  • A class defines many behaviors, which are selected by multiple conditional statements. Eliminate conditional statements by encapsulating each behaviour in a strategy.
Advantages of Strategy Pattern
  • Hierarchies of Strategy classes can be used to define a family of algorithms or behaviors for contexts to reuse.
  • Encapsulating the algorithm in separate Strategy classes lets you vary the algorithm independently of its context.
  • The Strategy pattern offers an alternative to conditional statements for selecting desired behavior. When different behaviors are Encapsulating different behaviours in different Strategy classes eliminates the need for conditional statements.
Drawbacks of Strategy pattern
  • A client must understand how Strategies differ to be able to select the right strategy. If possible, the context may be albe to this for you.
  • Strategy pattern increases the number of objects in an application.

2 comments:

Popular Posts