liveBook · Manning

Sport

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

A book-specific abstract C++ class representing a sport whose player-recruitment and venue-reservation algorithms are defined through abstract operations.

Sport models a sport as an abstract C++ class with a type and two operations: recruit_players() and reserve_venue(). Baseball, Football, and Volleyball initially inherit from it and implement both algorithms. section 8.2.2

The initial inheritance-based design exposes several practical weaknesses:

  • Duplicates algorithms such as returning "stadium" across multiple sport subclasses. section 8.2.2
  • Hardcodes players and venues, so changes require rewriting several classes. section 8.2.2
  • Makes shared algorithms difficult to reuse and leaves venue changes poorly encapsulated. section 8.2.2

With Strategy, Sport contains player and venue strategy objects instead of implementing those algorithms in subclasses. It calls their interfaces, can replace them at run time, and lets sports share implementations such as Stadium. section 8.2.3

Changing a venue at run time

A Volleyball object can initially use OpenField, then receive a Stadium strategy through set_venue_strategy(). Its report changes venue without changing the Volleyball class. 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.

Use the class diagram to compare the original subclass responsibilities with Sport's composed PlayerStrategy and VenueStrategy families. section 8.2.3

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

How deep it goes
Defines an abstract interface, contrasts inheritance with composition, and demonstrates runtime strategy replacement.
Examples
Uses Baseball, Football, Volleyball, BaseballPlayers, FootballPlayers, VolleyballPlayers, Stadium, and OpenField.
What it assumes
Assumes basic C++ inheritance and virtual functions while demonstrating abstract classes, interfaces, aggregation, and delegation.
What you can do after
Evaluate/understand how to separate sport objects from interchangeable recruitment and venue algorithms.
How it connects
Connects Sport to Strategy, inheritance, composition, Code to the Interface, Open-Closed, and Encapsulates What Varies 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.