How to use “Factory Method”
The Factory Method design pattern is a creational design pattern. This means that its main objective is to create objects. The official definition by GOF is as follows:
Define an interface for creating an object, but let the subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
Note 1: By “decide” in the definition above it does not mean that the subclass magically decides which object to create (at least not in a parameterized version of the Factory Method). The decision actually happens in the client; however, the work of creating the appropriate object that the client is going to work with is done by the subclass that overrides the Factory Method.
Note 2: This pattern relies on inheritance for creating objects. The current trend is to use the Abstract Factory Pattern, which relies on composition.
Note 3: By “client” I mean the calling code, the final user of the API that makes up the subsystem.
The Problem
Consider a simple application that deals with vehicles with the following hierarchy in the mind map below:
Question: What would happen if we want to create a particular type of vehicle and we do not use any kind of Factory Pattern?
That we would be giving the client the responsibility of having to know how to instantiate a particular type of Vehicle. As far as the client is concerned it just wants a Vehicle, then it’s going to do whatever he wants with it.
Question: What would happen if we add many more types (Car, Truck, Bike) and many more subtypes (Van, Sedan …)?
In this example it may not be as obvious as we only have three types of Vehicles (Car, Truck, and Bike) and two specific implementations under each. But if we had ten different cars, trucks, and bikes then the amount of if/else logic that you would have to do in the client in order to instantiate the right type would be quite tedious. This is considered boilerplate code at the same time that is difficult to maintain.
Question: What if you want to add a new type of Vehicle (e.g a Boat)?
If you do not use the Factory Method or other Abstraction layer you would have to make changes to the client to support that.
Solution
The Factory Method
Since the definition of the Factory Method states that the purpose is to defer instantiation of an object in the family to a subclass, then we have to make the class that will contain the factory method abstract. Also to ensure that subclasses are the ones really responsible for the creation of a particular object (in our case it will be a Vehicle) we have to provide with an abstract method, this way subclasses must provide the implementation. This method is what is popularly known as the factory method. It usually takes the name of createXYZ or newXYZ (that seems to be the industry standard for what I have seen) . It looks as follows:
package factorymethod;
public abstract class VehicleFactory {
//Factory method
abstract Vehicle newVehicle(String type);
}
The Common Interface
The client should work with a known interface, this way it will allow us to change the subsystem transparently. It will look as follows:
package factorymethod;
import java.util.List;
public abstract class Vehicle {
public abstract List<String> getFeatures();
public abstract List<String> getSpecs();
}
The Factory
A Car Factory would be responsible for knowing all the types that fall under the category of Car. Do you see how much cleaner is to have the branching logic in this factory rather than having a big method somewhere with all types in there? It would look as follows:
package factorymethod;
public class CarFactory extends VehicleFactory {
@Override
Vehicle newVehicle(String type) {
if(type.equals("Sedan")){
return new Sedan();
}else{
return new Van();
}
}
}
The Product
This is what the client asked for:
package factorymethod;
import java.util.List;
public class Sedan extends Vehicle{
//Put some specific properties of a SEDAN here
//Put some other specific methods of a SEDAN here (To differentiate from Van for example)
@Override
public List<String>getFeatures() {
//Put code to query your Car database here
return null;
}
@Override
public List<String>getSpecs() {
//Put code to query your Car database here
return null;
}
}
The Client
Notice how the client uses the appropriate factory to go get the specific type of product. If the client wanted a Bike for the example, the Car and Truck factories would be ignored. Also notice that since the client gets a generic Vehicle product you can add many more specific products transparently without affecting the client code. It looks as follows (You could improve the client using Reflection like done at the end of this other post) :
package factorymethod;
public class Starter {
public static void main(String[] args) {
VehicleFactory vehicleFactory = new CarFactory();
Vehicle vehicle = vehicleFactory.newVehicle("Sedan");
vehicle.getFeatures();
vehicle.getSpecs();
}
}
Now you could repeat what I have done above for the BikeFactory, and TruckFactory and its corresponding products as follows (Click on the image to enlarge):
Important: Your Specific “Products” should really be different (algorithm or logic wise)
While studying this pattern carefully from Head First Design Patterns (p.129) there was something that bothered me with their Pizzas example. If you look at all their specific Pizzas there wasn’t really any difference between the products, only String values!!! Yes that is different but what good is that in real life? If all that was read from a database for example you could get away with one class only. There was no need for 8 different Pizza types.
So my point is to make sure that you really have a different algorithm or logic in each specific product. Otherwise you will have added DRY (Don’t Repeat Yourself) in your application. (Unless I am totally missing something here
)
In our example we could say that we originally started our application supporting Cars only (Sedans and Vans), but then our application became popular and we decided to buy two existing databases that had support for Trucks(Pickup and Commercial) and Bikes(Scooter and DirtBike). Then it is safe to say that we need all these concrete objects as each getFeatures() and getSpecs() would contain an specific query targeting that particular data model and RDBMS.
Conclusions
Similar to the Adapter pattern where the main goal was to decouple the client from the actual implementation by giving it a known interface, the Factory Method Pattern also gives us that kind of flexibility. You should use a factory method:
- When you want to hide object creation knowledge from the client.
- When you want the client to always get a known interface. In this case, it will be an abstract object.
- When you want to add multiple implementations transparently in the future without affecting the client(s) API.
- To avoid branching “spaghetti code” when you have multiple variations of an object and you try to solve it by means of a lot of “if/elses” in a single location.
- When you have multiple variations of a particular object and you do not have a default one.
- It is also very good to illustrate how Polymorphism works.
Disadvantages:
- It depends on inheritance, so changes to the superclass can break existing code in subclasses. Inheritance usually requires thorough testing so Joshua Bloch in Effective Java recommends to use Composition over Inheritance.
- Joshua Bloch also recommends to use inheritance only when classes are designed for inheritance. (The factory method is designed for inheritance, so not really a disadvantage).
- This pattern is only good for a hierarchy of three levels. I have tried solving this with more levels and I had to much more inconveniences than advantages (had to create intermediate empty classes that were not bringing more information). For such situations, you should look into the Builder Pattern.






Hi Dario,
Great post, I´ve been looking for design patterns posts like this one for a while and you´ve nailed it! Well explained and to the point.
Good job!