What is factory pattern
Factory pattern is a creational pattern. It defines an interface for creating different type of object on the run-time. In this factory pattern, it is easy to scale-out when ever you want to add more type.
Example
Here is an example. Car is an abstract class. SmallCar,SedanCar and LuxuryCar extended Car class. CarFactory class has one static method to create different cars accroding to the input paramaters.
Car, it is a abstract class and has abstract showStage method inside.
java1
2
3
4
5
6
7
8
9
10
11
12
13package factorypattern;
public abstract class Car {
protected CarType model = null;
public Car(CarType model){
this.model =model;
System.out.println(model + " is made");
}
protected abstract void showStage();
}CarType, it is a enum type that store different type of cars
java1
2
3
4
5package factorypattern;
public enum CarType {
SMALL,SEDAN, LUXURY
}LuxuryCar, one type of car that extends Car class
java1
2
3
4
5
6
7
8
9
10
11
12
13
14package factorypattern;
public class LuxuryCar extends Car {
LuxuryCar(){
super(CarType.LUXURY);
showStage();
}
protected void showStage() {
System.out.println("Builing a "+this.model+ " car ..");
}
}SedanCar, one type of car that extends Car class
java1
2
3
4
5
6
7
8
9
10
11
12
13
14package factorypattern;
public class SedanCar extends Car{
public SedanCar() {
super(CarType.SEDAN);
this.showStage();
}
protected void showStage() {
System.out.println("Builing a "+this.model+ " car ..");
}
}SmallCar, one type of car that extends Car class
java1
2
3
4
5
6
7
8
9
10
11
12
13package factorypattern;
public class SmallCar extends Car {
public SmallCar() {
super(CarType.SMALL);
this.showStage();
}
protected void showStage() {
System.out.println("Builing a "+this.model+ " car ..");
}
}CarFactory, it provides a static method to create different type of cars according to the input
java1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24package factorypattern;
public class CarFactory {
public static Car buildCar(CarType model){
Car car = null;
switch (model){
case SMALL:
car = new SmallCar();
break;
case SEDAN:
car = new SedanCar();
break;
case LUXURY:
car = new LuxuryCar();
break;
default:
break;
}
return car;
}
}
TestFactoryPattern, there shows how we test factory method. In this main method, different cars will be created through static method of CarFactory.
java1
2
3
4
5
6
7
8
9package factorypattern;
public class TestFactoryPattern {
public static void main(String[] args) {
System.out.println(CarFactory.buildCar(CarType.SMALL));
System.out.println(CarFactory.buildCar(CarType.SEDAN));
System.out.println(CarFactory.buildCar(CarType.LUXURY));
}
}








