Skip to content

Instantly share code, notes, and snippets.

@johnborges
Created May 6, 2020 16:27
Show Gist options
  • Save johnborges/e0d56f2098e407ca6088a78febd2107c to your computer and use it in GitHub Desktop.
Save johnborges/e0d56f2098e407ca6088a78febd2107c to your computer and use it in GitHub Desktop.
7 Common JS Design Patterns
  1. Constructor
// This creates a new empty Object
var newObject = {};

// This creates a new empty Object
var newObject = Object.create(Object.prototype);

var newObject = new Object();
  1. Prototype
var myCar = {
  name: "Ford Escort",
  brake: function() {
    console.log("Stop! I am applying brakes");
  }
  Panic : function() {
    console.log ( "wait. how do you stop thuis thing?")
  }
}
var yourCar= Object.create(myCar);
// You can now see that one is a prototype of the other
console.log(yourCar.name);
  1. Module
function AnimalContainter (){
  const container = [];

  function addAnimal (name) {
    container.push(name);
  }

  function getAllAnimals() {
    return container;
  }

  function removeAnimal(name) {
    const index = container.indexOf(name);
    if(index < 1) {
      throw new Error('Animal not found in container');
    }
    container.splice(index, 1)
  }

  return {
    add: addAnimal,
    get: getAllAnimals,
    remove: removeAnimal
  }
}

const container = AnimalContainter();
container.add('Hen');
container.add('Goat');
container.add('Sheep');

console.log(container.get()) //Array(3) ["Hen", "Goat", "Sheep"]
container.remove('Sheep')
console.log(container.get()); //Array(2) ["Hen", "Goat"]
  1. Singleton
function DatabaseConnection () {

  let databaseInstance = null;

  // tracks the number of instances created at a certain time
  let count = 0;

  function init() {
    console.log(`Opening database #${count + 1}`);
    //now perform operation
  }
  function createIntance() {
    if(databaseInstance == null) {
      databaseInstance = init();
    }
    return databaseInstance;
  }
  function closeIntance() {
    console.log('closing database');
    databaseInstance = null;
  }
  
  return {
    open: createIntance,
    close: closeIntance
  }
}

const database = DatabseConnection();
database.open(); //Open database #1
database.open(); //Open database #1
database.open(); //Open database #1
database.close(); //close database
  1. Factory
  2. Observer
  3. Command
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment