Creational Patterns «Prev Next»

Factory Method Pattern - Exercise

Objective: Write an abstract Vehicle class. In this exercise, you will write an abstract Vehicle class that matches the structure shown in the UML diagram below.

UML diagram for an abstract Vehicle class and related members
UML diagram for the abstract Vehicle class

Implement an abstract base class named Vehicle. Your class should model a moving object with a speed that can increase and decrease over time.

Required Behavior

  • Use accelerate() and decelerate() to change the current speed.
  • Enforce the invariant:
    speed is always between 0 and maxSpeed (inclusive).
  • If a call would increase speed above maxSpeed, pin the value to maxSpeed.
  • If a call would decrease speed below 0, pin the value to 0.

C++ Note

If you are implementing this exercise in C++, overload the << operator instead of relying on a toString() method.

This Vehicle abstraction is intentionally broad and can describe many things (including pedestrians) as long as they follow the same speed constraints and interface.

Type or paste your answer below, then click Submit.