DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

2

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:

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (1)

Collapse
 
jangelodev profile image
João Angelo

Hi Nhan Nguyen
Your tips are very useful
Thanks for sharing

Dynatrace image

Frictionless debugging for developers

Debugging in production doesn't have to be a nightmare.

Dynatrace reimagines the developer experience with runtime debugging, native OpenTelemetry support, and IDE integration allowing developers to stay in the flow and focus on building instead of fixing.

Learn more