Polymorphism is a powerful tool that uses subclasses as instances of their common superclass. For instance, an abstract base class
Vehicle may be a
Bicycle, or a
Each of these subclasses behaves differently (for example, a
Bus does not accelerate as fast as a
but they all support the same
Vehicle interface; that is, they all have public
Many times they may not have any other public members than precisely those declared in the common superclass.
This allows client classes to be written without detailed knowledge of exactly which class they're working with.
The same code that works with a
Bus works with a
Car, with a
Motorcycle, with a
and so forth.
However, there is one exception: constructors. In Java and C++, constructors have the same name as their class.
This means that a subclass cannot override its parent's constructor; and, more importantly, constructors must be invoked explicitly.
When a client instantiates a class with
, that client must know at compile time exactly which class it is instantiating.
This penetrates the layer of abstraction
normally imposed by polymorphism and a common base class.
The Factory Method
pattern is used in circumstances like this to remove specific knowledge of which class to instantiate from the
client and instead place it inside the common base class and concrete subclasses where it belongs.
In particular, you should think of the Factory Method
when any of the following conditions hold:
You do not know at compile time which specific subclasses need to be instantiated.
You want to defer the choice of which objects to create to a subclass.
A class delegates its work to a helper class, and you want to remove explicit information about which class the work
is delegated to.
In this exercise, you will write a class that uses the Factory Method pattern.
Factory Method - Exercise