Appearance
Facade
Provide a unified interface to a set of interfaces in a subsystem. The Facade pattern defines a high-level interface that makes the subsystem easier to use.
The Facade pattern is a relatively simple design pattern with the following basic idea:
If a client needs to interact with multiple subsystems, the client would have to understand the interfaces of each subsystem, which can be cumbersome. If there is a unified "mediator" that the client can interact with, and that mediator then interacts with the subsystems, it simplifies things for the client. The Facade acts as that mediator.
Example: Company Registration
Suppose the process for registering a company involves three steps:
- Applying for a business license from the administrative department.
- Opening an account with a bank.
- Registering for a tax identification number with the taxation authority.
Here are the interfaces for the three subsystems:
java
// Business registration:
public class AdminOfIndustry {
public Company register(String name) {
...
}
}
// Bank account opening:
public class Bank {
public String openAccount(String companyId) {
...
}
}
// Tax registration:
public class Taxation {
public String applyTaxCode(String companyId) {
...
}
}
If the subsystems are complex and the client is not familiar with the process, all these steps can be delegated to a mediator:
java
public class Facade {
private final AdminOfIndustry admin = new AdminOfIndustry();
private final Bank bank = new Bank();
private final Taxation taxation = new Taxation();
public Company openCompany(String name) {
Company c = this.admin.register(name);
String bankAccount = this.bank.openAccount(c.getId());
c.setBankAccount(bankAccount);
String taxCode = this.taxation.applyTaxCode(c.getId());
c.setTaxCode(taxCode);
return c;
}
}
In this way, the client interacts only with the Facade, completing all the complicated steps of company registration in a single call:
java
Company c = facade.openCompany("Facade Software Ltd.");
Facade in Web Applications
Many web applications consist of multiple subsystems that provide services, and they often use a unified Facade entry point, such as a RestApiController
. This allows external users to only be concerned with the interface provided by the Facade without worrying about which internal subsystem actually processes the request.
In more complex web applications, there may be multiple web services. In such cases, a unified gateway is often used to automatically route requests to different web services. This gateway provides a unified entry point and can offer additional services such as user authentication and rate limiting. Essentially, this gateway functions as a Facade.
Exercise
Implement a "mediator" service for registering a company using the Facade pattern.
Summary
The Facade pattern provides a unified entry point for clients and hides the internal details of subsystem calls.