The factory pattern uses a function to hide the process of creating specific objects and returning their reference. It returns a new instance whenever the factory function is called.
Where to use Factory Pattern?
- The factory function is used in cases where the type of object is decided at run time.
- It is used in an application that manages, maintains, and modifies the collection of objects that are different but have methods and properties in common.
- It could be a collection of documents with a combination of XML documents, pdf documents.
- It could be also generating different invoices of purchase orders depending upon the product categories.
It provides reusability and main. The same factory function can be used to generate a similar type of object and it also allows us to add/remove new object functions seamlessly without changing a lot of code.
In the below example, we have created the factory method creatFlower for creating different types of flowers object and returning their reference in turn. Also, we have created two different objects for it named as flowerOne and flowerTwo for calling the factory method creatFlower and when we are passing the flower name such as Rose for flowerOne and Lily for flowerTwo objects it returns new instances of flowers whenever called.
Now run the above code and then open the browser developer tool by pressing the F12 key and select the Console tab and you should see the following logs in the Console tab.