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:

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (1)

Collapse
 
jangelodev profile image
João Angelo

Hi Nhan Nguyen
Your tips are very useful
Thanks for sharing

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay