Skip to content

Instantly share code, notes, and snippets.

@rkhaslarov
Last active July 14, 2022 10:46
Show Gist options
  • Save rkhaslarov/99f32d806c82cee6107d70e2291bc468 to your computer and use it in GitHub Desktop.
Save rkhaslarov/99f32d806c82cee6107d70e2291bc468 to your computer and use it in GitHub Desktop.
"Less popular" JavaScript Design Patterns
class Report {
constructor(consumer, products, preferences) {
this.consumer = consumer;
this.products = products;
this.preferences = preferences;
}
}
class ReportBuilder {
constructor() {
this.consumer = null;
this.products = null;
this.preferences = null;
}
setConsumer(consumer) {
this.consumer = consumer;
}
setProducts(products) {
this.products = products;
}
setPreferences(preferences) {
this.preferences = preferences;
}
build() {
return new Report(this.consumer, this.products, this.preferences);
}
}
const builder = new ReportBuilder();
builder.setConsumer({ name: 'Joe' });
builder.setProducts([{ product: 'French fries' }, { product: 'Burger' }]);
builder.setPreferences({ value: 'no ketchup' });
console.log(builder.build());
class Command {
execute() {}
}
class VolumeUpCommand extends Command {
execute() {
console.log('volume up');
}
}
class VolumeDownCommand extends Command {
execute() {
console.log('volume down');
}
}
const Messages = {
VOLUME_UP: 'volumeUp',
VOLUME_DOWN: 'volumeDown',
}
const Commands = {
[Messages.VOLUME_UP]: VolumeUpCommand,
[Messages.VOLUME_DOWN]: VolumeDownCommand,
};
class Executor {
handleMessage(payload) {
const { type } = payload;
if (!Commands[type]) {
console.warn('unknown command');
return;
}
const command = new Commands[type]();
command.execute(payload);
}
}
const executor = new Executor();
executor.handleMessage({ type: 'volumeUp' });
executor.handleMessage({ type: 'volumeDown' });
executor.handleMessage({ type: 'unknown' });
class HTMLProcessor {
parse() {
console.log('parsing html');
}
}
class XMLProcessor {
parse() {
console.log('parsing xml');
}
}
class DefaultProcessor {
parse() {
console.log('content type is not supported');
}
}
const SupportedContentTypes = {
HTML: 'html',
XML: 'xml'
}
function getProcessor(contentType) {
switch(contentType) {
case SupportedContentTypes.HTML:
return new HTMLProcessor();
case SupportedContentTypes.XML:
return new XMLProcessor();
default:
return new DefaultProcessor();
}
}
const processor = getProcessor('html');
console.log(processor.parse())
const processor1 = getProcessor('txt');
console.log(processor1.parse())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment