Published Apr 21, 2017

Design Patterns 101: What are the main differences between a (abstract) factory and a builder?

Design Patterns 101: What are the main differences between a (abstract) factory and a builder?

Abstract factory and Builder, both help in creating objects and are as such part of the creational design patterns. They vary in the context of their usage. Abstract factory is used for creating a family of objects, which share a common interface. Builder, on the other hand, is concerned with building a single type of object. Builders may also be abstract and its subclasses may have common logic to build a certain subpart. Obligatory examples follow:

Abstract factory:

Let’s assume that there is an AbstractPizzaFactory with its subclasses in Chicago and Naples (yum). The AbstractPizzaFactory will allow you to choose toppings like pepperoni and margherita. Now, the ChicagoPizzaFactory will serve you deep dish pizza, whereas NaplesPizzaFactory will give you Neapolitan pizza - both with the same toppings. Both of these are pizzas, but they will look and taste very different. main-qimg-80e9de673cd8b03665a6a4f218bfdbbf-c


Example 1: There is a CarBuilder, which builds a car by building its transmission system, engine, wheels, etc. There is also a BikeBuilder, which builds a bike using gear box, chains, etc (don’t really know the parts). There is no relation between a car and a bike, but both the builders may use the same vendors to procure parts like nuts and bolts and hence may extend the same abstract class VehicleBuilder.

Example 2: Let’s say your school/work canteen has a MealBuilder. To build a meal, first it’ll build a main course, say a burrito. Then it’ll prepare sides like fries. Finally, it’ll add a drink like soy milk.

Now let’s assume, the canteen vendor changes and now you have options to choose between a veg and a non-veg meal. Hence now, there are two subclasses present, VegMealBuilder and NonVegMealBuilder. Both builders will now have to build different objects, and they may not have the same parts. The veg meal still has a main, a side, and, a drink. The non-veg meal has a salad, a main, and a dessert. VegMealBuilder will prepare Mac-n-cheese, enchilada soup and soy milk for the veg meal. NonVegMealBuilder will give you mexican salad, chicken burger and pudding.