facade, Java, OOP, structural design pattern

Design Patterns: Facade

The facade design pattern is known as a structural design pattern.

The facade pattern is used to reduce complexity among classes. One way to achieve this goal is by providing a simplified interface to implement general facilities among objects.

That means we can use the facade in order to describe and implement the actions of objects. We can write a complex piece of code that performs an explicit task using some objects, and we are able to use this code again and again through facade without writing the same code all the time.

It is ideal to use it when we have some complex libraries which take effort to use. It provides us with a simpler interface to use those libraries without being concerned about how these libraries work internally.

Using facade, objects are decoupled, each promoting independence. It’s something like an entry point to our objects and also we are able to establish communication among them solely through the facade. That is how we can achieve decoupling.

The facade is a very easy design pattern to learn and that’s why you need to be careful using it. It is really easy to diverge from the right usage. This pattern has to be used not as a layer which handles data and takes decisions, but as a very high layer of the interface that just helps us simplify objects. For example, we need to execute a complex task that a person wants to book a flight and a hotel. If we don’t use facade, we have to implement every single task like date availability, destination, payment methods, and so on. On the other hand, using the facade, we are able to call only one method of facade class that performs all these actions for us.

How to use it

We can create an interface that is going to keep different implementations of our complex objects. Then we can communicate with these objects through the facade’s interface and the only thing that we need to be aware is to know the different implementations the interface offers us.

Example

Let’s see a real-world example. We have a web service that a user can log in and read some articles only if he has paid the subscription.

Let’s start with the user’s class.

The class which checks user’s credentials so as to give permissions to a user in the platform is the following.

The class checks if the user has paid his subscription and he is valid.

The class checks if the user has access to a specific article page.

Now the interface for the facade.

The implementation of the interface.

Facade pattern testing:

Output:

You can download the source code from GitHub.