Design Patterns: Facade

Facade design pattern is known as a structural design pattern.

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 facade in order to describe and implement actions of objects. We can write a complex piece of code which 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 of 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 facade. That is how we can achieve decoupling.

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 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, payments methods and so on. On the other hand, using 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 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 login and read some articles only if he has paid the subscription.

Let’s start with user’s class.

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

Class which checks if user has paid his subscription and he is valid.

Class which checks if user has access to a specific article-page.

Now the interface for facade.

The implementation of interface.

Facade pattern testing:

Output:

You can download the source code from GitHub.

2 Comments

  1. geodoo May 29, 2017 at 9:36 am

    Hi Lefteris!

    Congrats on the code! Super clean and elegant implementation!

    Keep up the good work!

    1. elefher May 29, 2017 at 9:44 am

      Thanks Geodoo

Comments are closed.