Sitemap
Sachin Patil

Sachin Patil

Loves coding, travelling, hiking, reading a lot everyday

Factory Method Pattern

2 min readJan 21, 2018

--

Can you “write an example of Factory Method pattern”? Someone may end up writing following code.

public interface Car {
int maxSpeed();
}
public class Civic implements Car {
public int maxSpeed() {
return 170;
}
}
public class Accord implements Car {
public int maxSpeed() {
return 155;
}
}
public class CarFactory {
public Car produce(String type) {
Car car;
if ("civic".equals(type)) {
car = new Civic();
} else if ("accord".equals(type)) {
car = new Accord();
} else {
car = DummyCar()
}
// Label Car's maximum speed
return car;
}
}

He may call method “produce(type)” as Factory Method pattern. What if I create Utils class which has same produce(type) method? What will be difference between these two implementations? Why should I call produce(type) method as Factory Method?

Above implementation is NOT a Factory Method pattern. It’s not even considered as design pattern.

Now, let’s consider cars in countries like India and US.

Get Sachin Patil’s stories in your inbox

Join Medium for free to get updates from this writer.

Same car model in India and US have differences in driver seat location, maximum speed, number of gears, etc. So, Region specific factory needs to produce cars for given region.

Code will be like below:

public class abstract CarFactory {
public Car produce(String type) {
Car car = getCar(type);
// Label car speed
return car;
}

public abstract Car getCar(String type);
}
public class IndiaCarFactory extends CarFactory {
public Car getCar(String type) {
if ("civic".equals(type)) {
return new IndiaCivic();
} else if ("accord".equals(type)) {
return new IndiaAccord();
}
return new IndiaDummyCar();
}
}
public class USCarFactory extends CarFactory {
public Car getCar(String type) {
if ("civic".equals(type)) {
return new USCivic();
} else if ("accord".equals(type)) {
return new USAccord();
}
return USDummyCar();
}
}

Here, CarFactory uses Car to label maximum speed on it. However, it does not create instances of Car by its own. Rather, it defers creation of Car instances to its subclasses i.e. regional factory. This deferring to subclasses to get concrete instances via method is very important to call this pattern as Factory Method.

Method getCar(type) is “interface” provided by super class for subclasses to create instances and provide them back for usage. So,

Define an interface for creating an object, but let subclasses decide which class to instantiate. The Factory method lets a class defer instantiation it uses to subclasses. — GoF

Here is difference between two UML diagrams of above code examples.

--

--

Sachin Patil
Sachin Patil

Written by Sachin Patil

Loves coding, travelling, hiking, reading a lot everyday