JS-Design Patterns: Factory Pattern

Adarsh Singh
1 min readMay 26, 2019

--

JS provides an easy way to create an object. The object literal syntax. But that is useful to create one instance of an object. What if you want to create multiple objects with similar characteristics? The solution is to have a factory which produces such objects.

This leads us to the “Factory Pattern”. A creational design pattern.

Factory Pattern — ES6

One important thing to note in this pattern is that it does not use the new keyword.

A function which is not a class or constructor, that returns an object, is called a factory function. In JavaScript, any function can return an object. When it does so without the new keyword, it’s a factory function.

Gist below.

This factory function can be used to create multiple Fruit objects. Each of them will have the properties of name, color, and taste. Also, a method to set the color of the fruit.

Related topics: new keyword, default parameters, destructuring objects in JS

--

--