liveBook · Manning

Strategy

As explained in Object-Oriented Software Design in C++

A strategy is an encapsulated algorithm or policy that can be selected as one of multiple interchangeable ways to perform an operation.

A strategy encapsulates one algorithm or policy among interchangeable alternatives. Use it when an operation must support multiple algorithms that can vary independently from their clients. section 8.0 section 8.2.3

Compose a client with strategy interfaces instead of making subclasses implement every variation. The client delegates operations to its current strategies and can replace them at run time. section 8.2.3

A strategy-based design provides these practical benefits:

  • Encapsulates algorithm changes inside classes implementing the strategy interfaces. section 8.2.3
  • Supports extension with new sports without changing the Sport superclass. section 8.2.3
  • Reuses shared code such as Stadium across baseball and football. section 8.2.3

Sports teams and venues

Sport aggregates PlayerStrategy and VenueStrategy objects. Baseball selects BaseballPlayers and Stadium; Volleyball initially selects VolleyballPlayers and OpenField, then replaces its venue strategy with Stadium at run time. section 8.2.3

Figure 8.6 This version of the application is modeled from the Strategy Design Pattern for the sport teams and venues. The player family of algorithms implement the PlayerStrategy interface, and the venue family of algorithms implement the VenueStrategy interface. Class Sport uses has-a relationships to aggregate the algorithms. Each player and venue algorithm has a strategy() member function. The Baseball, Football, and Volleyball subclasses are now much simpler, and each one sets the player_strategy and venue_strategy member variables of the Sport superclass.

Inspect the composition of Sport with player and venue strategy families, interfaces, and simpler sport subclasses. section 8.2.3

How Object-Oriented Software Design in C++ covers it

How deep it goes
Defines strategy interfaces, concrete implementations, composition, delegation, replacement, and resulting design benefits.
Examples
Uses baseball, football, and volleyball player strategies with stadium and open-field venue strategies.
What you can do after
Apply the pattern by defining interfaces, composing strategies into a client, and changing implementations at run time.
How it connects
Connects composition, aggregation, Code to the Interface, Open-Closed, Encapsulates What Varies, and Don't Repeat Yourself principles.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Object-Oriented Software Design in C++. The section links point to the parts of the book it draws on.