Details on how to implement a simple Factory Pattern in JavaScript.
Problem
Here is an example of code that could use some refactoring.
Let’s say we have 4 plugins (plugin1, plugin2, ..) which all have different methods (exec1, exec2, ..).
var plugin1 = require('./plugin1'); |
We are loading 4 plugins and call methods on these plugins. The problem comes from all the duplicated require statements at the beginning.
Factory Pattern
Our Factory pattern can help us encapsulate the creation of all these objects.
Meet the pluginFactory
:
// Plugin Factory Object |
In our client code (index.js
), we can write:
var pluginFactory = require('./pluginFactory'); |
We have direct access to the plugins and their methods. This is great because we have replaced all the require statements with one and we don’t need our client code (index.js
) to know about the plugins path anymore.