Facade Design Pattern in C#
This Blog represents the third segment in our design patterns series, where we’ve previously explored the Decorator and Adapter design patterns.
What is Facade Design Pattern ?
Facade is structural design pattern which simplifies complex systems ( classes or libraries) to simple solution using interface.
Example
Recently while working with .NET Web APIs I came up with a situation where I had multiple classes.
RolesService class with following methods :
-
CreateRoleAsync
-
UpdateRoleAsync
-
DeleteRoleAsync
-
GetRoleByIdAsync
-
GetRolesListAsync
Above class has 10 more methods, on similar fashion I had UserService, CurrenciesService and AccountsService with 10+ methods in each class.
I was only interested in RoleIds, CurrencyIds, AccountIds and UserIds.
So instead of creating instance for each service and calling needed methods, I created a FacadeClass named MasterService and injected services in its constructor.
Then I added an interface with 4 methods (GetRoleIds, GetAccountIds, GetCurrencyIds, GetUserIds) which I was looking.
MasterService implemented that interface IMasterService.
In my desired controller/class I only injected the Facade Interface (IMasterService) and called the methods
What did we achieve ?
By doing so, I encapsulated the complexity of the underlying services and provided a simplified interface (IMasterService) that only includes the methods I was interested in (e.g., retrieving RoleIds, CurrencyIds, AccountIds, and UserIds).
This way, your controller or class only needs to interact with the MasterService facade, making the code more manageable and modular.
Benefits of Facade ?
Following are the benefits of facade :
-
Provides a unified and simplified interface to a subsystem.
-
Promotes loose coupling, isolating clients from subsystem implementation changes.
-
Improves code readability by offering a clear entry point to the subsystem.
-
Hides internal subsystem details, promoting encapsulation.
-
Facilitates integrating new subsystems without impacting existing client code.
-
It’s possible that you’ve employed the Facade pattern in the past without explicitly recognizing it.
Whenever you're ready, there are 3 ways I can help you:
- Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
- Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
- Patreon community : Get access to all of my blogs and articles at one place