DEV Community

The Factory Pattern - Design Patterns meet the Frontend

Colum Ferry on December 09, 2019

Picture this. A Car Dealership selling Cars 🚗. Suddenly, they want to branch out and sell Trucks 🚛. You had initially programmed the order and sale...
Collapse
 
fly profile image
joon • Edited

A project I recently worked on a project that turned out to really need this kind of structure, but I only realized this when it was a bit too late.
A very informational read, especially the 'when should I use this' part. :)
Thank you dearly

Collapse
 
coly010 profile image
Colum Ferry

You're more than welcome!

Collapse
 
jenc profile image
Jen Chan

Very helpful breakdown and I feel like I’ve come across it in early lessons of OO JS, but especially as applied to front end components, so much easier to understand, thanks

Collapse
 
coly010 profile image
Colum Ferry

You're welcome!

Collapse
 
chase2981 profile image
Chase Gibbons

Good post and all, but could you show us how to create a factory which doesn’t violate the open/closed principle? (I.e. a factory which when adding a third let’s say “PrintDialogue”, or whatever, a factory which doesn’t require modifying the factory’s code just to add another implementation) Maybe something that uses metadata from the children to determine what to do for instance? Thnx.

Collapse
 
coly010 profile image
Colum Ferry

There's a more advanced form of the Factory Pattern which makes it easier to stay aligned with the Open Closed Principle, called the Abstract Factory Pattern: en.wikipedia.org/wiki/Abstract_fac...

However, in the implementation above, while the factory itself violates the open/closed principle, the Dialog itself doesn't and the factory aids you in adhering to it.

You implement the Dialog, thus extending it, rather than modifying it and you use the abstract to interface with the concrete implementation returned from the Factory.

Collapse
 
awakeel profile image
Abdul wakeel

Thank you, This is what I was looking for.

Collapse
 
jannikwempe profile image
Jannik Wempe

Thanks for explanation and the good examples :-)
As you said, you don't like the fact that it relies on inheritance: wouldn't it be possible to create a factory that uses composition instead?

Collapse
 
coly010 profile image
Colum Ferry

I'm not entirely sure. I mean, you could essentially have a bunch of behaviour classes that you piece together within the factory and return that new object, but I feel like that borders a different pattern, The Builder Pattern, potentially.