Creational Patterns «Prev Next»

Vehicle Factory Consequences - Exercise

VehicleFactory Class

Objective: Write an abstract class called VehicleFactory in place of direct instantiation with constructors.

In this exercise, you will continue building the course project by creating an abstract factory class that produces Vehicle objects through a single creation method rather than calling constructors directly from client code.

UML diagram for the abstract VehicleFactory class with probability fields and a createVehicle method.
UML Summary: VehicleFactory
  • Private fields: chanceCar, chanceBus, chanceBicycle, chancePedestrian (all double)
  • Constructors: a no-args constructor and a constructor that sets all probability fields
  • Factory Method: createVehicle(): Vehicle (abstract)

The intent is to centralize object creation so clients call createVehicle() and never need to know which concrete vehicle subtype is instantiated.

How this fits the workflow

You already created concrete Vehicle subclasses (Car, Bus, Bicycle, Pedestrian). Now you will write the creation layer that decides which subclass to create, keeping client code decoupled.

Requirements

It is common to create separate factories like CarFactory or BusFactory. For this simulation, however, your factory should return different vehicles with different frequencies. The percentages (probabilities) are configured through constructor arguments.

Constructors

  • No-args constructor: sets default probabilities.
  • Parameterized constructor: accepts (chanceCar, chanceBus, chanceBicycle, chancePedestrian).

Default probabilities

  • chanceCar = 0.80
  • chanceBus = 0.10
  • chanceBicycle = 0.10
  • chancePedestrian = 0.00

Validation constraints

  • No probability may be negative.
  • The sum of all chances must be ≤ 1.0 (100%).

Factory Method

  • Declare an abstract method: public abstract Vehicle createVehicle();
  • The method implementation will be provided later by a concrete subclass (or subclasses). For this exercise, focus on the abstract base class design, constructor behavior, and validation.

Submit your solution

In the text area below, type or paste your VehicleFactory abstract class. Then click Submit to view the reference solution on the result page.