Factory Design Pattern
To begin exploring Factory design pattern, first of all, we need to know what factories are. Factories are simply functions that create objects and return them. In most cases you can use factories to design to code instead of classes, and they are much simpler and more readable than classes.
Even though classes have a lot of better performance, it is a good idea to use factories unless otherwise you are in a situation that requires you to instantiates many objects. For example, factories will take averagely 0.0004 milliseconds to create an object in most case while class will take 0.0002 milliseconds to create an object; classes will reduce the time to half way as compare to factories. This comes to matter when you are creating about thousands of classes but when your classes are not that much you will never notice the difference and hence, will not be necessary.
Why do we need factory design pattern? Now let think of it this way; in our codes, we uses a lot of objects. We have classes that instantiate object from class and we use them in many difference ways. In a strategy pattern, we use dependency injection where we imagine ahead of time what the objects will be doing. But at some point in our programming, that imagination has to be constructed. That is we need to instantiate our objects and the question is, where do we do that? This is what factory pattern try to address. In this regards, we say, when you are about to instantiate, let encapsulate them such that it span uniformly across all places so that you can use factory whenever you want to instantiate and the factory is responsible for instantiating appropriately.
Factory pattern gives you the ability to create objects without specifying the exact class of object that will be created; a class is chosen at run time using polymorphism.
For the matter, one will want to use factory pattern design when a method returns one of several possible classes that share a common super class. It is also a good idea to use factory design pattern to design your code when you do not know ahead of time what class object you will need. It is again useful when all of the potential classes are in the same subclass hierarchy and when you do not want the user to have to know every subclass in your code.
I chose to explore this topic as because I was unable to understand it on the go when we were treating it in class and I also got confused as to which pattern to use for my upcoming project and I decided to write this blog on factory pattern because I am impressed how you can use factories instead of classes to provide a clear code. I am actually redesigning my previous code using the factory pattern and I can figure out that everything looks simple at this point.
Reference: https://airbrake.io/blog/design-patterns/factory

From the blog CS@Worcester – Computer Science Exploration by ioplay and used with permission of the author. All other rights reserved by the author.