Facade Design Pattern

Design Pattern Tutorial Series

Facade Design Pattern in Java - 5-Step Guide

The Facade Pattern is based on the concept of simplifying activities. It allows us to wrap complex procedures in a facade class and afterwards utilize these procedures by one simple method call. For this reason it is categorized as a structural design pattern.

 

This design pattern likely does not sound all that new to you, as it is common for developers to use it without knowing it.

Table of Contents

facade-design-patterns-in-java-overview-INTEGU

Step 1 - The Objective

The objective of this tutorial will be to collect rent payments as a landlord. The landlord owns four different apartments and require certain steps to be done to gain the payments.

These steps include, finding the address of the apartment (the landlord constantly forgets where they are), contacting the tenant (the tenants always need to be reminded to pay their rent), and finally collect the payment.

As we can see from the description, the landlord really needs some help.

The secondary objective is to simplify the whole process, so that the landlord only needs to request the rent payments once. We want the landlord to forget all about the current messy procedures.

However, before we determine how the solve the objective with the facade pattern, let’s see how it could be solved without any design patterns at all.

facade-design-patterns-in-java-objective-INTEGU

Step 2 - Working Without The Facade

If we were to solve the main objective without the facade pattern, it would imply that we are working with the complex procedure directly in the working context.

As described in the previous section, the procedure of collecting rent requires three steps: finding the tenant’s address, contacting the tenant, and collecting the payment.

Each of the three steps are part of the Apartment-class. In the current context we have four instances of this class, which means that we would have to make twelve method calls to collect rent for all four apartments. (3 [Calls/Apartment] x 4 [Apartments] = 12 [Calls])

As we can see from the code example, this actually solves the main objective of collecting the rent. However, it does not help our landlord to fulfill the secondary objective of simplifying the procedure.

Since the landlord still have to manage the whole procedure for each apartment, the amount of code in the working context will continue to grow. This type of code does not uphold the DRY (Don’t Repeat Yourself) principle, neither is it maintainable (e.g. too long method – Link), and finally it leaves a code smell. (e.g. main-method does more than one thing – Link)

To say the least, this piece of code suffers from many problems. How to solve this? Well, let’s take a look at the facade pattern and see if it can help us out.

 

facade-design-patterns-in-java-disadvantage-INTEGU
public class Main {
    public static void main(String[] args) {
        Apartment john = new Apartment("John", "Wall Street 1", 5000);
        john.findAddress();
        john.contactTenant();
        john.collectPayment();
        Apartment sally = new Apartment("Sally", "Baker Street 20", 4000);
        sally.findAddress();
        sally.contactTenant();
        sally.collectPayment();
        Apartment tim = new Apartment("Tim", "Broadway 110", 2500);
        tim.findAddress();
        tim.contactTenant();
        tim.collectPayment();
        Apartment jane = new Apartment("Jane", "Green Street 90B", 1000);
        jane.findAddress();
        jane.contactTenant();
        jane.collectPayment();
    }
}

Step 3 - Concept Of The Facade Pattern

The facade design pattern is as mentioned in the introduction, rather simple. You have most likely already used it multiple times without being aware of it being a design pattern.

The concept of the pattern is to extract any type of procedure into its own class. This allows the procedure to be utilized through only one method call. Sounds like a dream for our landlord.

Additionally, this also means that the procedure can be used multiple times from the working context, without having to repeat code. Thereby we also uphold the DRY principle.

If you understand this concept, you have grasped the facade design pattern. There is nothing more to it. Let’s therefore quickly move onto the class diagram and code sample to see the pattern in action.

facade-design-patterns-in-java-advantage-INTEGU

Step 4 - Class Diagram (UML)

The class diagram of the facade design pattern does not require any extension or implementations. Instead it relies on the working context to have an instance of the facade class.

Likewise, the facade class, then has-an instance of all necessary objects required to perform the complex procedure. In our scenario, the complex procedure only requires interaction with one object type (Apartment), but that could in theory have been multiple types of objects.

That concludes the facade pattern’s class diagram. Finally, it is time to dive into the code.

facade-design-patterns-in-java-class-diagram-INTEGU

Step 5 - Code (Java)

Given that code is sometimes difficult to learn through concepts and theory, I provide the code for the example.

Hopefully, this will be sufficient for you to learn to identify and implement the composite pattern in your future endeavors as a software developer.

The Apartment

public class Apartment {
    private final String tenantName;
    private final String address;
    private final int rentPayment;
    public Apartment(String tenantName, String address, int rentPayment) {
        this.tenantName = tenantName;
        this.address = address;
        this.rentPayment = rentPayment;
    }
    public void contactTenant() {
        System.out.println(tenantName + " has been contacted.");
    }
    public void collectPayment() {
        System.out.println(rentPayment + "$ has been collected in rent payment.");
    }
    public void findAddress() {
        System.out.println("The address of this apartment is " + address);
    }
}

The Facade

import java.util.ArrayList;
public class SimpleLandLord {
    ArrayList listOfApartments = new ArrayList();
    public void collectRent() {
        listOfApartments.forEach(apartment -> {
            apartment.findAddress();
            apartment.contactTenant();
            apartment.collectPayment();
        });
    }
    public void addApartment(Apartment apartment) {
        listOfApartments.add(apartment);
    }
}

How to use the Facade Pattern

public class Main {
    public static void main(String[] args) {
        SimpleLandLord simpleLandLord = new SimpleLandLord();
        simpleLandLord.addApartment(new Apartment("John", "Wall Street 1", 5000));
        simpleLandLord.addApartment(new Apartment("Sally", "Baker Street 20", 4000));
        simpleLandLord.addApartment(new Apartment("Tim", "Broadway 110", 2500));
        simpleLandLord.addApartment(new Apartment("Jane", "Green Street 90B", 1000));
        simpleLandLord.collectRent();
    }
}

Recommended Reading

Article

  • Theoretical walkthrough – Source Making – Blog
  • Practical walkthrough – Tutorialspoint – Blog
  • Practical walkthrough – Springframework Guru – Blog
  •  

Video Tutorial 

  • Theoretical  (based on “Head-First: Design Patterns”) – Christopher Okhravi – YouTube
  • Practical – Derek Banas – YouTube

Books

Tools

  • Camtasia – Used for illustrations – Camtasia

About

Hi, I'm the Author

My name is Daniel H. Jacobsen and I’m a dedicated and highly motivated software developer with a masters engineering degree within the field of ICT. 

I have through many years of constantly learning and adapting to new challenges, gained a well-rounded understanding of what it takes to stay up to date with new technologies, tools and utilities. 

The purpose of this blog is to share both my learnings and knowledge with other likeminded developers as well as illustrating how these topics can be taught in a different and alternative manner.

If you like the idea of that, I would encourage you to sign up for the newsletter.

Cheers! 🍺

Didn't Find What You Were Looking For?

Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
Scroll to Top
INTEGU - Cookie-consent

INTEGU uses cookies to personalize your experience and provide traceability for affiliate links. By using the website, you agree to these terms and conditions. To learn more see the privacy policy page.