Last active
November 13, 2021 22:54
-
-
Save pascalvree/f437472fdeaf6fe25556 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//////////////////////////////////////////////////////////////////////////////////////////////////// | |
// (Framework) Factory Module code | |
class Registry { | |
constructor() { | |
this.registry = { }; | |
} | |
add(key, value) { | |
this.registry[key] = value; | |
} | |
get(key) { | |
return this.registry[key]; | |
} | |
} | |
class Factory { | |
constructor(registry) { | |
this.registry = registry; | |
} | |
throwException(msg, Type) { | |
throw new Type(msg); | |
} | |
createInstance(classname) { | |
var type; | |
try { | |
type = this.registry.get(classname).createInstance(); | |
} catch(err) { | |
this.throwException("The type for \"" + classname + "\" isn't registered", TypeError); | |
} | |
if(type === undefined) { | |
this.throwException("The type for \"" + classname + "\" isn't registered", TypeError); | |
} | |
return type; | |
} | |
} | |
//////////////////////////////////////////////////////////////////////////////////////////////////// | |
// (Framework) Transformations Module code | |
class NoTransformation { apply(str) { return str; } } | |
class NoTransformationFactory { createInstance() { return new NoTransformation(); } } | |
class Md5Transformation { apply(str) { return str.toUpperCase(); } } | |
class Md5TransformationFactory { createInstance() { return new Md5Transformation(); } } | |
class Rot13Transformation { apply(str) { return str.toLowerCase(); } } | |
class Rot13TransformationFactory { createInstance() { return new Rot13Transformation(); } } | |
var transformationsRegistry = new Registry(); | |
transformationsRegistry.add('NoTransformation', new NoTransformationFactory()); | |
transformationsRegistry.add('Md5', new Md5TransformationFactory()); | |
transformationsRegistry.add('Rot13', new Rot13TransformationFactory()); | |
var factory = new Factory(transformationsRegistry); | |
//////////////////////////////////////////////////////////////////////////////////////////////////// | |
// Consumer/Project specific code | |
class Rot18Transformation { apply(str) { return str.replace('a', '..xx..'); } } | |
class Rot18TransformationFactory { createInstance() { return new Rot18Transformation(); } } | |
transformationsRegistry.add('Rot18', new Rot18TransformationFactory()); | |
console.log( | |
factory.createInstance('Md5').apply("abc"), // => Success | |
factory.createInstance('Rot13').apply("aBc"), // => Success | |
factory.createInstance('Rot18').apply("abc") // => Success | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment