Factory Methods are most common when programmers know at compile time that they need to instantiate an instance of a subclass
of a common base class but they do not know which concrete subclass to instantiate.
For example, they know the
Vehicle class but not the
The Factory Method pattern defers the decision of which subclass to instantiate to happen at runtime.
The Factory Method pattern has several variations. What unites them all is that a nonconstructor method creates instances of a class.
The main variant of the Factory Method uses an abstract
Creator class to create instances of an abstract
Concrete subclasses of the
Creator class create particular concrete instances of the
Another popular variation is called the parameterized Factory Method.
This uses a single, generally concrete,
Creator class with a single Factory Method to create instances of
different subclasses. The subclass instantiated is chosen based on the arguments passed to the Factory
openConnection() method of
java.net.URL is an example of a parameterized Factory Method.
In this exercise, you will write four subclasses for the
Concrete Subclasses - Exercise