Toy is an abstract C++ superclass for concrete objects such as ToyCar, ModelAirplane, and TrainSet. It defines what each toy is, how it plays, and what sound it makes through virtual member functions. section 7.3
The design evolves as its drawbacks become visible:
- Inheritance first groups toys under Toy, but subclasses duplicate behaviors and hardcode each play action and sound. section 7.3
- Separate PlayAction and Sound classes reduce duplication, but inheritance-based combinations still leave each toy tied to chosen behaviors. section 7.3
- Toy then aggregates PlayAction and Sound objects, allowing behaviors to be shared, selected during construction, and changed with set_play() or set_sound(). section 7.3
- ToyFactory::make() encapsulates new and selects a concrete toy from a Kind value at run time. section 7.4
Configurable toys
A car can use Roll and Engine, an airplane can use Fly and Engine, and a train can initially use Roll and ChooChoo. Replacing the train’s sound with Engine changes its printed behavior without changing TrainSet. section 7.3
Figure 7.2 This version of the application uses is-a relationships between the Toy subclasses and their superclass. Two design faults are the duplicated code, which violates the Don’t Repeat Yourself Principle, and the hardcoded play action and sound behavior of each toy.
Use the design diagram to compare the original inheritance-heavy Toy hierarchy with its duplication and hardcoding problems. section 7.3
