Façade Pattern
The word Façade in general context indicates the exterior of the building hiding the interior complexity. In the similar fashion it is used to hide the complexity of interactions across multiple classes by providing an outer façade which interacts with these classes.
Client calls Façade which handles the complex interactions instead of client dealing with the interactions. It would make sense in a scenario where you have multiple clients and you don’t want these complex interactions to take place with client instead to have a façade which does that. The Façade pattern provides a unified interface to a set of interfaces in subsystem. Façade defines a higher-level interface that makes subsystem easier to use.
UML Diagram
UML diagram below shows a unified interface Façade dealing with complex interactions of subsystem. The client instead of interacting with the subsystem directly uses Façade which makes subsystem easier to use.
Code
The Facade class provides a simple interface to the complex logic of one or several subsystems. The Facade delegates the client requests to the appropriate objects within the subsystem. The Facade is also responsible for managing their lifecycle. All of this shields the client from the undesired complexity of the subsystem. The Facade’s methods are convenient shortcuts to the sophisticated functionality of the subsystems. However, clients get only to a fraction of a subsystem’s capabilities.
The Subsystem can accept requests either from the facade or client directly. In any case, to the Subsystem, the Facade is yet another client, and it’s not a part of the Subsystem. The client code works with complex subsystems through a simple interface provided by the Facade. When a facade manages the lifecycle of the subsystem, the client might not even know about the existence of the subsystem. This approach lets you keep the complexity under control. Below is C# code example for Façade pattern.
Law of Demeter
Facade Pattern is also referred to as Law of demeter or principle of least knowledge which are used to implement least coupling. In sloppy way Law of demeter says you are only allowed to say A.B but you are not allowed to say A.B.C, which means that you are allowed to talk to yourself and you are allowed to talk to things you know but you are not allowed to talk to things of things you know. Like you are allowed to talk to yourself, your friends but you are not allowed to talk to friends of friends. Following this statement causes interfaces wider which helps to decouple classes.
GitHub Link: Facade Pattern#8DayOf100DaysOfCode
Comments