DEV Community

Cover image for JavaScript Design Patterns - Factory Pattern

JavaScript Design Patterns - Factory Pattern

KristijanFištrek on November 10, 2019

Welcome to my new development series where I try my best to explain design patterns by using JavaScript! What is a design pattern? In s...
Collapse
 
macsikora profile image
Pragmatic Maciej • Edited

Hello Kristijan.
Want to add some things here. You are very much setting a context of this pattern in class based environment. Also implementation use Class with one method. The reality is - factory is just a function, and it simplify data structure creation.

const makeVehicle = (name, type) => ({name, type});
const makeCar = (name) => makeVehicle(name, 'car');
const makeTruck = (name) => makeVehicle(name, 'truck');

// end even more concise by point free
const makeVehicle = (type) => (name) => ({name, type});
const makeCar = makeVehicle('car');
const makeTruck = makeVehicle('truck');

Enter fullscreen mode Exit fullscreen mode

Let me repeat again, factory is just a function which allows in centralized way to create structures in proper shape, thanks to that we are sure that the created object has proper structure and somebody did not missed some fields or done some typo (very often in JS world)

Its simple thing. There is no reason to complicate it.

Collapse
 
kristijanfistrek profile image
KristijanFištrek

I agree!
And damn, that code looks nice and neat 😁

Being a backend developer, I am still adjusting to this whole JS.
Would you say I completely missed mark with this or am I on a good path of applying a factory pattern into the JS structure?
Any advice is warm welcomed!

Collapse
 
macsikora profile image
Pragmatic Maciej

It depends what language are you used to. Looking on the example, looks like something very OOP like Java or C#. Not like what you are writing is wrong. Just you need to take into consideration that every time you don't need to use this probably you don't need a class. Keep up with a good work!

Thread Thread
 
kristijanfistrek profile image
KristijanFištrek

Thank you! \m/

Collapse
 
milburngomes profile image
MilburnGomes

Great Article! Design Patterns are very essentials to apply in today's world. A must book to read for design patterns is 'Erich Gamma, Richard Helm, Ralph Johnson, John M. Vlissides - Design Patterns Elements of Reusable Object-Oriented Software'
Thanks for sharing!

Collapse
 
kristijanfistrek profile image
KristijanFištrek

I agree! As I am building more and more robust applications, design patterns are saving the day 😁

Haven't read that one! I shall take a look. Thanks for the recommendation! 🤘