Factory Pattern in JavaScript

2016-05-12

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, ..).

index.js
1
2
3
4
5
6
7
8
9
var plugin1 = require('./plugin1');
var plugin2 = require('./plugin2');
var plugin3 = require('./plugin3');
var plugin4 = require('./plugin4');

plugin1.exec1();
plugin1.exec2();
plugin1.exec3();
plugin1.exec4();

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:

pluginFactory.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Plugin Factory Object
var PluginFactory = function() {
// Plugin List
var plugins = [
{propertyName: 'plugin1', path: './plugin1'},
{propertyName: 'plugin2', path: './plugin2'},
{propertyName: 'plugin3', path: './plugin3'},
{propertyName: 'plugin4', path: './plugin4'}
];

// Enumerate through plugins and assign them to Object Properties
for(var i = 0; i < plugins.length; i = i + 1) {
this[plugins[i].propertyName] = require(plugins[i].path);
}
};

// Export an instance of the Factory
module.exports = new PluginFactory();

In our client code (index.js), we can write:

index.js
1
2
3
4
5
6
var pluginFactory = require('./pluginFactory');

pluginFactory.plugin1.exec1();
pluginFactory.plugin2.exec2();
pluginFactory.plugin3.exec3();
pluginFactory.plugin4.exec4();

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.