Factory pattern is a part of creational pattern. In Factory Pattern, we do not create an object directly. But we determine type of the object in the factory class. This pattern implements interface in the base class where an object type is determine in factory class.
Below is code example of Factory Pattern. In this example we use Java programming language
Step 1, Create interface
public interface PublicTransport {
void transport();
}
Step 2, Create subclass where interface implementation is done differently
public class Plane implements PublicTransport {
@Override
public void transport() {
System.out.println("The plane take passengers by air");
}
}
public class Bus implements PublicTransport {
@Override
public void transport() {
System.out.println("The bus take passengers by land");
}
}
public class Ship implements PublicTransport {
@Override
public void transport() {
System.out.println("The ship take passengers by ocean");
}
}
Step 3, Create factory class to create the object
public class TransportFactory {
public PublicTransport createTransport(String transportType){
if(transportType == null) return null;
switch(transportType.toLowerCase()){
case “plane”:
return new Plane();
break;
case “bus”:
return new Bus();
break;
case “ship”:
return new Ship();
break;
default:
return null;
}
}
}
Step 4, Use factory class to create objects
public class MainClass {
public static void main(String[] args) {
TransportFactory transportFactory = new TransportFactory();
// Create plane object and call transport method
PublicTransport plane = transportFactory.createTransport("plane");
plane.transport();
// Create bus object and call transport method
PublicTransport bus = transportFactory.createTransport("bus");
bus.transport();
// Create ship object and call transport method
PublicTransport ship = transportFactory.createTransport("ship");
ship.transport();
}
}
Step 5, Run the code
The plane take passengers by air
The bus take passengers by land
The ship take passengers by ocean
This Factory Pattern is very useful if we want to extend the object type. Because if the design was we create the business entity by defining object type directly, it will be coupled tightly. And it will be quite difficult to scale up the system.