What is difference between Factory Design Pattern and Builder Pattern?

Answer: Listing here the differences between factory design pattern and Builder design pattern with example and source code.

  • A Factory Design Pattern is used when the entire object can be easily created and object is not very complex. Whereas Builder Pattern is used when the construction process of a complete object is very complex.
BUILDER:  Construction process of creating a complete Car object is very complex.
//Code snips of Builder
MarutiCarBuilder implements IBuilder{
	
	void addEngine(){}
	void addTyre(){}
	void addPaint(){}
	void addBody(){}
}

FACTORY:

public class StationeryFactory {

	// Factory method Stationary
	public static IStationery getStationery(String type) {		
		
		if (type.equals("PEN")) {
			return new Pen();

		} else if (type.equals("PENCIL")) {
			return new Pencil();

		}else{
			return null;
		}
	}
}

  • Another difference is if we want to add another object into Factory, we need to modify the factory method- violates open close principle (close for modification and open for extension). Whereas, if want to add another car builder we can just create another builder and no change in director class as director constructor accept all builders– Extensible.
BUILDER:
//Code snips of Builder
MarutiCarBuilder implements IBuilder{
	
	void addEngine(){}
	void addTyre(){}
	void addPaint(){}
	void addBody(){}
}

//Another Builder object
FordCarBuilder implements IBuilder{
	
	void addEngine(){}
	void addTyre(){}
	void addPaint(){}
	void addBody(){}

}

Related Posts