Lesson 5 | Factory Method: motivation |
Objective | Write an abstract Vehicle Class |
Write an abstract Vehicle Class
Polymorphism is a powerful tool that uses subclasses as instances of their common superclass.
For instance, an abstract base class called Vehicle
may be a Car
, a Bicycle
, or a Bus
. Each of these subclasses behaves differently (for example,
a Bus
does not accelerate as fast as a Car
) but they all support the same Vehicle
interface;
that is, they all have public start()
, stop()
, and accelerate()
methods.
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 are working with.
The same code that works with a Bus
works with a Car
, with a Motorcycle
, with a Bicycle
, and so forth.
Factory Method Motivation
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
new
, 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.
Abstract VehicleFactory Class
public abstract class VehicleFactory {
public static final String LUXURY_VEHICLE = "Luxury";
public static final String NON_LUXURY_VEHICLE = "Non-Luxury";
public abstract Car getCar();
public abstract SUV getSUV();
}//End of class
Concrete Factory Subclasses of the Abstract VehicleFactory Class
public class LuxuryVehicleFactory extends VehicleFactory {
public Car getCar() {
return new LuxuryCar("L-C");
}
public SUV getSUV() {
return new LuxurySUV("L-S");
}
}//End of class
public class NonLuxuryVehicleFactory extends VehicleFactory {
public Car getCar() {
return new NonLuxuryCar("NL-C");
}
public SUV getSUV() {
return new NonLuxurySUV("NL-S");
}
}//End of class
Factory Method - Exercise