GithubHelp home page GithubHelp logo

design-patterns-javascript's Introduction

Design Patterns in Javascript

Solutions to commonly occuring problems in software design. Can be considered as templates that can be used to solve different problems

Types of design patterns

  • Creational design pattern

    Methods for creating objects in a specific situation withour revealing the creation method.

    • Constructor

    • Abstract

    • Prototype

    • Singleton

    • Builder

    • Factory

  • Structural design pattern

    These are concerned about class/object composition and relationship between objects. They let us to add new features / functionalities so that restructuring some parts of system do not affect the rest.

    • Facade

    • Aadapter

    • Composite

    • Bridge

    • Flyweight

    • Proxy

    • Decorator

  • Behavioral design pattern

    Concerned with the communication between dissimilar objects in system. They streamline the communication and make the information synchronised between objects.

    • Chain of Responsibility

    • Strategy

    • Interpreter

    • Command

    • Observer

    • Iterator

    • Mediator

    • Visitor

    • Memento

    • State

    • Template Method

    • Revealing Module

  • Architectural design pattern

    Used for solving the archetectural problems wihtin a given context in software architecture.

    • MVC

    • MVP

    • MVVM

Creational Patterns

Factory Pattern

  • Template to create objects.
  • Used in complex situations where the type of object required varies and needs to be specified in each case.
  • It does not use the new keyword to instantiate the objects.
  • It provides a generic interface that delegates the object creation responsibility to corresponding subclass.

class IceCreamFactory {
constructor() {
this.createIcecream = function (flavour) {
let iceCream;
if (flavour === "chocolate") {
iceCream = new Chocolate(flavour);
} else if (flavour === "mint") {
iceCream = new Mint(flavour);
} else if (flavour === "strawberry") {
iceCream = new Strawberry(flavour);
}
return iceCream;
};
}
}
class Chocolate {
constructor(flavour) {
this.iceCreamFlavour = flavour;
this.message = function () {
return `You chose the ${this.iceCreamFlavour} flavour`;
};
}
}
class Mint {
constructor(flavour) {
this.iceCreamFlavour = flavour;
this.message = function () {
return `You chose the ${this.iceCreamFlavour} flavour`;
};
}
}
class Strawberry {
constructor(flavour) {
this.iceCreamFlavour = flavour;
this.message = function () {
return `You chose the ${this.iceCreamFlavour} flavour`;
};
}
}

Testing:
const iceCreamFactory = new IceCreamFactory();

const chocolate = iceCreamFactory.createIcecream("chocolate");
const mint = iceCreamFactory.createIcecream("mint");
const strawberry = iceCreamFactory.createIcecream("strawberry");

console.log(chocolate.message());
console.log(mint.message());
console.log(strawberry.message());
Output
You chose the chocolate flavour
You chose the mint flavour
You chose the strawberry flavour

Constructor Pattern

  • Use constructor present in class to create specific type of object.

Using Constructor function

function Human(name, age, occupation) {
this.name = name;
this.age = age;
this.occupation = occupation;
this.describe = function () {
console.log(`${this.name} is a ${this.age} years old ${this.occupation}`);
};
}

Testing
const human = new Human("Harshit", 29, "engineer");
human.describe();
Output
Harshit is a 29 years old engineer

Using Class

class Person {
constructor(name, age, occupation) {
this.name = name;
this.age = age;
this.occupation = occupation;
}
describe() {
console.log(`${this.name} is a ${this.age} years old ${this.occupation}`);
}
}

Testing
const person = new Person("Harshit", 29, "engineer");
person.describe();
Output
Harshit is a 29 years old engineer

when to use

  • libraries
  • plugins

Singleton Pattern

  • It restricts the instantiation of a class to a single object.
  • On next try, existing instance is returned, no new instance is returned.
  • example : printer to be used in office. Single instance is required so that everyone can use it, instead of having a new instance for each employee.

let instance = null;
class Printer {
constructor(pages) {
this.display = function () {
console.log(`You are connected to the printer. You want to print ${pages} pages.`);
};
}
static getInstance(numOfPages) {
if (!instance) {
instance = new Printer(numOfPages);
}
return instance;
}
}

Testing
var object1 = Printer.getInstance(2);
console.log(object1);
object1.display();

var object2 = Printer.getInstance(3);
console.log(object2);
object2.display();

console.log(object1 === object2);
Output
Printer { display: [Function (anonymous)] }
You are connected to the printer. You want to print 2 pages.
Printer { display: [Function (anonymous)] }
You are connected to the printer. You want to print 2 pages.
true

when to use

  • services : different service instances in application should be single instance.
  • databses : single connection in an application
  • configuration

Builder Pattern

  • Helps in building complex objects using simpler objects.
  • It provides flexible and step by step approach to construct objects.
  • It keeps representation and process of creation shielded

class Meal {
constructor() {
this.make = function (builder) {
builder.step1();
builder.step2();
builder.step3();
builder.step4();
return builder.get();
};
}
}
class MealBuilder {
constructor(pattie, side, soda) {
this.meal = null;
this.step1 = function () {
this.meal = new Order();
};
this.step2 = function () {
this.meal.addBurger(pattie);
};
this.step3 = function () {
this.meal.addSide(side);
};
this.step4 = function () {
this.meal.addSoda(soda);
};
this.get = function () {
return this.meal;
};
}
}
class Order {
constructor() {
this.burger = null;
this.side = null;
this.soda = null;
}
addBurger(pattie) {
this.burger = pattie;
}
addSide(side) {
this.side = side;
}
addSoda(soda) {
this.soda = soda;
}
display() {
console.log(`Your meal has a ${this.burger}, ${this.side} on the side and a ${this.soda}`);
}
}

Testing
var meal = new Meal();
var mealBuilder = new MealBuilder("chicken", "curly fries", "coke");
var chickenBurgerMeal = meal.make(mealBuilder);

chickenBurgerMeal.display();
Output
Your meal has a chicken, curly fries on the side and a coke

when to use

  • When complex objects are to be made.
  • example, DOM elements - plenty of nodes and attributes.

design-patterns-javascript's People

Contributors

harshitbhat avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.