Facade Pattern — A Quick Guide

Design Patterns: Facade Pattern

Emre Tanrıverdi
2 min readJun 6, 2021

“Facade Pattern provides a unified interface that is easier to use for sets of interfaces in a subsytem.”

Photo by Yusuf Evli on Unsplash

Simple Example:
Suppose you are going to build a house and there are lots of steps to achieve this. You need to build walls and a roof, buy furnitures, paint the walls etc…
You may just want to paint the walls as standalone feature in the future,
but it would be good to have an all-in-one package for building a house, as we need a complete house right now.

Real-Life Example:
Suppose you are writing an app and you need to make HTTP requests.
You need to tweak it with different variations of configurations according to your needs.

It would be best if you do all the configurations inside a method and just call that method from client code for simplified usage.

Implementation

public class HttpClientFacade {
private final HttpClient httpClient;

public HttpClientFacade(HttpClient httpClient) {
this.httpClient = httpClient;
}

public JsonObject getRequest(String url, String agentName) {
httpClient.setConnectTimeout(5000);
httpClient.expectCompression(true);
httpClient.setHeader("agentname", agentName);
//...
//...
return httpClient.get(url);
}
}

When you need to add/remove a property during GET request, you just need to implement it into this method and it’ll be a quick and an easy change.
Other parts of the code don’t need to know the details of getRequest.

And the client code will be like:

HttpClient httpClient = new HttpClient();
HttpClientFacade httpClientFacade =
new HttpClientFacade(httpClient);
httpClientFacade.getRequest("emretanriverdi.medium.com", "itsme");

Facade and Adapter both wrap multiple classes, but a Facade’s intent is to simplify, while an Adapter’s is to convert the interface to something different.

Thank you for reading and being a part of my journey!

Reference(s)

  • Head First Design Patterns. by Eric Freeman, Elisabeth Robson, Bert Bates, Kathy Sierra. Released October 2004. Publisher(s): O’Reilly Media, Inc.

--

--