Facade Pattern — get the gist in 2 min.
The facade pattern is all about providing a high-level interface that makes other domain functions easier to use and manage.
You might already have used this pattern knowingly or unknowingly.
The core principle behind the facade pattern is to provide a unified interface to access/manage other subsystems in the application.
Think about using a Facade pattern when :
— you want to provide a simple interface to the client and manage all complex handshakes between different subsystems somewhere else.
— you want to introduce a layered approach to your application then Think about using a Facade pattern.
Facade pattern is a type of structural design pattern where it helps to provide layered, decoupled structure.
Simple Example :
Consider you are writing a function for adding a product to the cart, it’s expected to do the below things when you add the product to the cart.
Adding Product To Cart
1. check if the request is from the registered customer if not show a registration popup.
2. check if the product is available in the warehouse (inventory check)
3. if the product is available in the warehouse then add the product to the cart and show a notification to the customer.
Well, you have different services for the above 3 points which you can use in your client class directly but don’t you think the client is least concerned about internal things happening when the customer is adding a product to the cart? means the client class is only expecting an interface for addProductToCart but what internally happens is not a direct concern of the client class.
This is where we can add layers and decouple internal logic, internal subsystem calls when a product is added to the cart.
Please click here for github code.
Please refer below structural diagram for the above example :
Q. How facade pattern can help decouple things and provide a more managed structure?
This is done by providing a unified interface, observe below diagram there are three flows where multiple subsystems are used, AddProductToCart, RemoveProductFromCart, PlaceOrder all these flows need different subsystems calls, instead of instantiating/ referring to those either via composition or inheritance it’s better to delegate calling these subsystems to facade class where facade class can provide a unified interface as well as manage all calls to different subsystems.
The real fun is in the details, if you wish to know and understand the pros-cons, java-code example for the facade pattern then please consider checking the detailed article at [facade-pattern-explained-using-java-4-min-read]
Thanks for reading. Love IT, Live IT, Enjoy IT.
On the journey to understand the core essence of design patterns.
Every Tuesday I publish a small 2 min post and a long 5–10 min post along with a code example, please consider following the publication if you wish to get notified!