Skip to content

Commit

Permalink
chapter 02: making encoderFactory open for extension injecting factories
Browse files Browse the repository at this point in the history
  • Loading branch information
devcorpio committed Mar 30, 2019
1 parent a14b46f commit b06e05d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 11 deletions.
21 changes: 10 additions & 11 deletions chapter-02-the-open-closed-principle/refactor/encoderFactory.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,21 @@
const jsonEncoder = require('./jsonEncoder');
const xmlEncoder = require('./xmlEncoder');
const yamlEncoder = require('./yamlEncoder');

function encoderFactory() {
const factories = {};

function createForFormat(format) {
if (format === 'json') {
return jsonEncoder();
} else if (format === 'xml') {
return xmlEncoder();
} else if (format === 'yml') {
return yamlEncoder();
if (typeof factories[format] !== 'function') {
throw new Error('Unknown format');
}

throw new Error('Unknown format');
return factories[format];
}

function addEncoderFactory(format, fn) {
factories[format] = fn;
}

return {
createForFormat,
addEncoderFactory,
};
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const encoderFactory = require('./encoderFactory');
const jsonEncoder = require('./jsonEncoder');

const encoderFactoryIstance = encoderFactory();

encoderFactoryIstance.addEncoderFactory('json', () => {
return jsonEncoder();
});

encoderFactoryIstance.createForFormat('json');

//... xml, yaml...

0 comments on commit b06e05d

Please sign in to comment.