DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

JavaScript Design Patterns - Structural - Facade

Image description

The facade pattern provides a simplified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem more straightforward to use.

In the below example, we are creating a simple interface Cart that abstracts all the complexity from several subsystems such as Discount, Shipping, and Fees:

class Cart {
  constructor() {
    this.discount = new Discount();
    this.shipping = new Shipping();
    this.fees = new Fees();
  }

  calc(price) {
    price = this.discount.calc(price);
    price = this.fees.calc(price);
    price += this.shipping.calc();

    return price;
  }
}

class Discount {
  calc(value) {
    return value * 0.85;
  }
}

class Shipping {
  calc() {
    return 500;
  }
}

class Fees {
  calc(value) {
    return value * 1.1;
  }
}
Enter fullscreen mode Exit fullscreen mode

Use this pattern when we want to provide a simple interface to a complex subsystem.

A complete example is here 👉 https://stackblitz.com/edit/vitejs-vite-ecb4hx?file=main.js


I hope you found it helpful. Thanks for reading. 🙏

Let's get connected! You can find me on:

Top comments (1)

Collapse
 
jangelodev profile image
João Angelo

Hi Nhan Nguyen
Your tips are very useful
Thanks for sharing