The other day, a friend asked me on how I go about choosing a design pattern in a given scenario, because it was not always very clear.

Some design patterns are similar in terms of functionality (i.e. factory vs. builder)

I presented my intuitions via chat, and at the end of the discussion we both realized that with these intuitions for some of the design patterns in mind, choosing next time among them will be easier.

Hence, I thought of documenting and sharing it with everyone.

Factory

Say that you are shopping from a factory outlet of a clothing company. You will only get t-shirts based on the size grades i.e. S, M, L, XL etc.

Hence, single input from our side i.e. S, M, L, XL etc. will define the whole t-shirt.

_Similarly, when you want to specify a single input argument like a keyword or an ENum, and get a variation of the main __abstract class/interface TShirt _created for you like SmallSizeTShirt, then you should go with Factory pattern.

Similar example is covered here, with abstract class/interface Person and its custom variations Villager and CityPerson created for use that are created on the basic of a single input, the enum PersonType.

Image for post

Factory Design Pattern in C#. Source: Wikipedia

Builder

Now say that instead of going to a factory outlet, you want to have something that fits you better, so you went to a tailor for custom tailored shirt.

Now, the tailor will take note of various other inputs like your chest size, your arm length, your shoulder length etc.

Hence, you can see that the tailor doesn’t have grades based on only one input like size, instead he has a number of input parameters and is makes unique shirts for each customer based on the input values for each of them.

Here, tailor is synonymous with a builder.

Hence, when there are multiple inputs from your side to construct a variation of the main abstract class/interface Shirt, use ShirtBuilder to return a CustomShirt for you based on various inputs.

Similar example is covered here, with ICarBuilder using various inputs like NumDoorsColourBrandName and ModelName and some code logic to construct a Ferrari 488 Spider Car.

#design-patterns #system-design-interview #java #python #software-engineering

HeadStart System Design — Design Pattern Intuitions
1.60 GEEK