Factory Pattern using Factory Method- Part 1

Why the need for factory pattern?

Let’s take example of a ToyotaCarFactory, the main aim of the ToyotaCarFactory is to fulfill an order for a ToyotaCar. There are multiple models of Toyota and the factory should manufacture them all.

The orderCar method would look something like this – 

ToyotaCar orderCar(String model)
{
    ToyotaCar car;

    if(model.equals("sienna") {
       car = new SiennaToyotaCar();
    } else if(model.equals("highlander") {
       car = new HighLanderToyotaCar();
    } else if(model.equals("prius") {
       car = new PriusToyotaCar();
    } 

    car.assembleParts();
    car.polish();
    car.testDrive();
}

If Toyota decided to launch three other methods, the object instantiation part would keep on increasing. And we would need to change it, make sure nothing breaks, add the code to correct part. Our code is not closed for modification, as every time new type of toyota car is added, we have to open this and modify it. 

If instead we would have implemented against a CarFactory interface, then we would have given the responsibility of instantiating the required objects to the subclasses.  And say other car manufacturers want to use the same CarFactory, we could easily add new concrete subclasses without causing changes to existing ones. 

That’s the advantage of coding to interfaces as opposed to coding to concrete implementation. Your code is following the principle of “Open for extension, closed for modification”.

Factory Pattern

Creator is the interface which has the factory method. But the subclasses which implement the factory method actually create the Product objects.

Example

Let’s use an example to better understand this pattern.

Example of Factory Pattern using Toyota Car manufacturing

Continuing on our Car manufacturing example, our Creator is the CarFactory, having the createCar() factory method which would hold the object instantiation part. ToyotaCarFactory is our concrete creator class which would be responsible for creating the different ToyotaCar objects by providing an implementation of createCar() method. 

We will see a sample implementation in the following post.


One response to “Factory Pattern using Factory Method- Part 1”