A strategy is a “template class”, where a template method contains the generic algorithm skeleton.

  • Parts of an algorithm are delegated to a strategy, hook methods are overwritten in sub-classes of strategy to provide the specific steps.
  • Template and hook methods are implemented in different classes and objects so can be exchanged at runtime.
  • Also uses polymorphism to enable variability.

Benefits:

  • Easily separate core logic and variation points.
  • Easily provide many different implementations of the details and use the one you need.
  • Functionality can be varied at runtime.

Disadvantages:

  • Object Schizophrenia

    Needs an additional object leading to “Object Schizophrenia

    • this in the strategy object refers to the strategy object but outside clients only know about the context. Meanwhile in the context object, this means the context object.
    Link to original
  • Can’t easily vary multiple aspects of the algorithm.