| Lesson 6 | Factory Method: structure |
| Objective | Develop the subclasses for the Vehicle Class. |
In the previous lesson and exercise, you defined an abstract Vehicle base class and enforced a key invariant:
0 ≤ speed ≤ maxSpeed. That base class is the “Product” abstraction in Factory Method terms—it defines a stable
contract that all concrete vehicles must honor.
This lesson is about the next step: developing concrete subclasses (such as Car, Truck, or Bicycle) so client code can work with the abstract Vehicle type while the system decides which concrete vehicle to instantiate.
Factory Method is most useful when you know you need some subclass of a base type, but you do not want to hard-code which one. In our running example:
Vehicle at compile time,Car, Truck, or Bicycle until runtime.When you create concrete subclasses correctly, you unlock these design benefits:
Vehicle methods without caring about the exact type.The classic GoF structure uses two abstract types above the “water line”:
Vehicle)Vehicle)Concrete implementations exist below the water line:
Car)
Product interface.ProductfactoryMethod() : Product
Product.CreatorConcreteProduct.Product),In this module’s vehicle example:
Vehicle (abstract base class)Car, Truck, Bicycle, etc.Vehicle (e.g., createVehicle())
Your task in this lesson is to build the ConcreteProduct layer: the subclasses that extend Vehicle
and provide any additional behavior or identifying information required by the exercise (for example, a concrete getType()
in C++, or a useful toString() / type label in Java).
A common variation is the parameterized Factory Method. Instead of an abstract creator hierarchy, you have a single creator method that takes a parameter and decides which product subclass to instantiate based on the argument.
This design appears frequently in modern APIs because it centralizes creation logic in one place. A classic Java example is
java.net.URL.openConnection(), which returns a URLConnection whose concrete type depends on the URL scheme.
Product.factoryMethod(parameter) : ProductConcreteProduct, while exposing the return type as Product.Product.In modern codebases, you’ll often see Factory Method concepts expressed through dependency injection, provider registries, or service discovery mechanisms. Even then, the design goal is the same: keep client code stable by returning abstractions, not concrete classes.
If you later combine this pattern with techniques like configuration files, environment variables, or feature flags,
you can select which Vehicle subclass to create at runtime without changing or recompiling client code.
Vehicle class.