JavaScript Design Patterns - Structural - Facade
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;
}
}
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:
Hashnode: https://nhannguyen.hashnode.dev/
X (formerly Twitter): https://twitter.com/nhannguyendevjs/
Buy Me a Coffee: https://www.buymeacoffee.com/nhannguyendevjs