The Strategy Pattern

According to the Gang of Four, the Strategy pattern's intent is to

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it.[6]

[6] ibid, p. 315.

The Strategy pattern is based on a few principles:

  • Objects have responsibilities.

  • Different, specific implementations of these responsibilities are manifested through the use of polymorphism.

  • There is a need to manage several different implementations of what is, conceptually, the same algorithm.

  • It is a good design practice to separate behaviors that occur in the problem domain from each other—that is, to decouple them. This allows me to change the class responsible for one behavior without adversely affecting another.

The Strategy Pattern: Key Features

Intent Allows you to use different business rules or algorithms depending upon the context in which they occur.
Problem The selection of an algorithm that needs to be applied depends upon the client making the request or the data being acted upon. If you simply have a rule in place that does not change, you do not need a Strategy pattern.
Solution Separates the selection of algorithm from the implementation of the algorithm. Allows for the selection to be made based upon context.
Participants and Collaborators
  • Strategy specifies how the different algorithms are used.

  • The ConcreteStrategies implement these different algorithms.

  • The Context uses the specific ConcreteStrategy with a reference of type Strategy. The Strategy and Context interact to implement the chosen algorithm (sometimes the Strategy must query the Context). The Context forwards requests from its Client to the Strategy.

Consequences
  • The Strategy pattern defines a family of algorithms.

  • Switches and/or conditionals can be eliminated.

  • You must invoke all algorithms in the same way (they must all have the same interface). The interaction between the ConcreteStrategies and the Context may require the addition of getState type methods to the Context.

Implementation Have the class that uses the algorithm (the Context) contain an abstract class (the Stragegy) that has an abstract method specifying how to call the algorithm. Each derived class implements the algorithm as needed. Note: this method wouldn't be abstract if you wanted to have some default behavior. Note: In the prototypical Strategy pattern, the responsibility for selecting the particular implementation to use is done by the Client object and is given to the context of the Strategy pattern.

Figure 14-6. Standard, simplified view of the Strategy pattern.



..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.114.132