/ Gists / Builder
On gists

Builder

JS Patterns

builder.js Raw #

/* 
  URL: https://learn.coderslang.com/0076-javascript-design-patterns-builder/ 
*/

// how create object from literal
const Employee = {
  isAdmin: false,
  getRole: function() {
	  return this.isAdmin ? 'Admin' : 'RegularEmp';
  };
};

const emp1 = Object.create(Employee);
emp1.getRole(); //'RegularEmp'

const emp2 = Object.create(Employee);
emp2.isAdmin = true;
emp2.getRole(); //'Admin'


// BUILDER PATTERN (prenasi a pomaha tvorit objekty s mandatory parametry, nepovinne vytvori separatne)

class OTG {
	constructor(model, color, maxTemperature, maxTimeSelection) {
	  this.model = model;
	  this.title = 'OTG';
	  this.color = color;
	  this.maxTemperature = maxTemperature || 150;
	  this.maxTimeSelection = maxTimeSelection || 30;
	}
}

const redOTG = new OTG('LG', 'red');
const highTempOTG = new OTG('LG', 'black', 200);
const highendTimeOTG = new OTG('LG', 'red', '150', '60');


class OTGBuilder {
  constructor(model, color) {
    this.model = model;
    this.title = 'OTG';
    this.color = color;
  }
  setMaxTemperature(temp) {
    this.maxTemperature = temp;
    return this;
  }

  setMaxTimeSelection(maxTime) {
    this.maxTimeSelection = maxTime;
    return this;
  }

  build() {
    return new OTG(this.model, this.color,
    this.maxTemperature, this.maxTimeSelection);
  }
}

const basicOTG = new OTGBuilder('MorphyRichards', 'Black')
  .setMaxTemperature(250)
  .setMaxTimeSelection(60)
  .build();
  
  // or without mandatory params
  const default = new OTGBuilder('Generic OTG', 'White')
  .build();

builder2-inline.js Raw #

// We declare our objects
const bug1 = {
    name: "Buggy McFly",
    phrase: "Your debugger doesn't work with me!"
}

const bug2 = {
    name: "Martiniano Buggland",
    phrase: "Can't touch this! Na na na na..."
}

// These functions take an object as parameter and add a method to them
const addFlyingAbility = obj => {
    obj.fly = () => console.log(`Now ${obj.name} can fly!`)
}

const addSpeechAbility = obj => {
    obj.saySmthg = () => console.log(`${obj.name} walks the walk and talks the talk!`)
}

// Finally we call the builder functions passing the objects as parameters
addFlyingAbility(bug1)
bug1.fly() // output: "Now Buggy McFly can fly!"

addSpeechAbility(bug2)
bug2.saySmthg() // output: "Martiniano Buggland walks the walk and talks the talk!