What is Facade Pattern?
Provide a unifed interface to a set of interaces in a subsystem. Facade defines a higher-level interface that makes the susystem easier to use.
When to use?
When we create a system, we divide it into subsystems to reduce the complexities. We assign specific responsibilites to the subsystem classes by following the Single Responsibility Principle. But, often depedencies between the susystems exist. In addition, clients individually interacting with the subsystem classes to fullfil a business requirement can result in a significant level of complexity.
Let's talk about an E-Commerce application. Where:
- Inventory Service: Check if the product is in stock
- Payment Service: Create payment for a given order
- Shopping Service: 3rd party to deliver the product
Take a look at the above diagram, we have 3 different clients.
- Mobile App
- Web App
- Desktop App
3 different clients communicate with 3 differnet service, and all of them are working independently. But, lets say we have a new Service layer to integrate in our existing system.
We can do easily, right? No.
- First, we have to design the new service layer for our system
- Second, since all of the clients are working independently with different service, we have to integrate the new service layer to all of the 3 different clients ends. Which is kinda sucks. Becuase we don't wanna work on 3 different clients if something changes again.
Then, what's the solution?
We can solve this problem by using the "Facade Design Pattern". Our client doesn't have to be acknowledged about what kind of services are working behind a order. Client just want to make an order without any kind complexitiy.
The Facade Design Pattern is a way of providing a simple way for the clients to interact with the subsystems. By working through a facade, now we can make changes to the subsystem classes without affecting the client code. In short, we make clients loosely couple with the subsystem classes.
Now, here is the above diagram. We have introduced a new layer between those 3/4 service layers, which is responsible to create an order for the client.
- Facade: Delegates client requestes to the appropiate subsystem classes
- Subsystem Classes: Business Logic/Internal functionalites
- Client: Requests the facade to perform some action
Let's a look at the implementation in Kotlin::
Follow me on LinkedIn: