Facade is a structural design pattern: 🖤🖤🖤🤍🤍
What is Facade?
Facade is a design pattern that provides a simplified (but limited) interface to a complex system of classes, library or framework. It helps to hide the complexity of the subsystems and provide a single point of access for the clients.
Imagine you want to enter a building that has many subsystems such as elevator, security and reception. You don’t want to deal with each subsystem separately, you just want to enter the building easily and quickly.
Why use Facade?
Facade reduces the overall complexity of the application and helps to move unwanted dependencies to one place. It also makes the code more readable and maintainable.
- It isolates the clients from the complexity of the subsystems.
- It provides a simple and unified interface to the subsystems.
- It promotes loose coupling between the clients and the subsystems.
- It can become a god object that is coupled to all the classes of the subsystems.
- It can limit the functionality and flexibility of the subsystems for the clients.
- It can violate the open/closed principle if new features or changes are required in the subsystems.
Question: I hate the Facade, what are the alternatives?
Answer: You can use direct communication with the subsystems, but you will have to deal with more complexity and dependencies.
When to use Facade?
Question: When do I need to use Facade?
Answer: You should use Facade when you need to provide a simple interface to a complex system, when you want to reduce coupling between clients and subsystems, or when you want to organize subsystems into layers.
You have three classes that represent different subsystems of a building: Elevator, Security, Reception
Each class has its own methods and logic.
You want to create a simple interface for entering the building that hides the details of the subsystems:
How to implement Facade?
You can use direct communication with the subsystems, but you will have to create and manage each object separately. This will increase the complexity and coupling of your code.
You can create a facade class that provides a simple interface for entering the building. The facade class will create and manage the objects of the subsystems internally. This will reduce the complexity and coupling of your code.
The facade class
BuildingFacade provides a simple interface
enter to the complex subsystems of
Reception. The client code only interacts with the facade class and does not need to know the details of the subsystems.
Facade is a useful design pattern when you want to simplify the interaction between clients and subsystems. It can help you reduce complexity, improve readability and maintainability, and promote loose coupling. However, you should also be aware of the potential drawbacks of using a facade, such as creating a god object, limiting functionality and flexibility, and violating the open/closed principle.