Patterns
YouTube Video for the Facade Pattern in Java and Python
This article exists on YouTube

The entire content of this article is also available on YouTube. It's your choice: if you prefer video content, you can watch it on YouTube. If you prefer reading, feel free to continue here.

Head over to the YouTube video

What is a Facade Pattern?

The Facade Pattern is a programming pattern used in software engineering and is part of the group of structural patterns. It may be used in any object-oriented programming language, such as Java, Python, C++, and so on. What it does is to provide a simplified interface or class to some larger already existing logic. This way it makes the case easier to understand and to work with. It encapsulates the interactions between the client and the subsystem, hiding the details of the implementation. This means that only the necessary functionality is exposed to the client and the readability can therefore be improved.

In more simple terms, there could be a big system at hand that needs to be controlled. To get from one system state to another there may be a lot of steps required to achieve that, and even more steps to come back to the original system step. Now, one way to achieve the change of system states would be to repeat every necessary step every single time and also possibly in different unrelated situations. This can be cumbersome and error-prone, and may also anicipate desire for alternative ways for achievement of objectives. Hence, the other way would be to make use of the Facade Pattern to reduce complexity yet achieve the exact same result.

The Facade Pattern does not hide the complex system away. It just creates a new simplified view on the same system. After having created the simplified new way using the Facade Pattern, access to some complex system behind the facade is still the same and unchanged as before.

What is the structure of a Facade Pattern?

  1. Facade
    The Facade class itself is the intermediary that simplifies access to a complex system. It acts as a single point of interaction for the client code, shielding them from the intricacies of the underlying functionalities.
  2. Subsystem Class
    The Subsystem Class refers to the individual classes or functionalities that make up the complex system. These classes are hidden behind the Facade, meaning the client code doesn't interact with them directly.

Example Codes

There are a number of programming languages where the Facade Pattern can prove useful. Every language that supports the construct of classes can make use of this pattern.

All the codes within this article can also be found on the GitHub repository programming-patterns and in there within the directory Facade Pattern.

Java Example

The following example is a Java application putting the Facade Pattern into action. All the following files need to be placed into the same folder so that the code within the files can work properly, because the files also reference each other. Being the smallest possible code example, this little project consists of four Java files:

  1. SubsystemClass1.java
  2. SubsystemClass2.java
  3. Facade.java
  4. Main.java

For this example to work the first thing to do is create subsystem classes having methodes that do something. In our case we create the SubsystemClass1 that has a method operationOne() and SubsystemClass2 that has a method operationTwo().

public class SubsystemClass1 {
    public void operationOne() {
        System.out.println("Subsystem class 1 calls operation one.");
    }
}
public class SubsystemClass2 {
    public void operationTwo() {
        System.out.println("Subsystem class 2 calls operation two.");
    }
}

The next thing is to create the Facade class that holds references to instances of the subsystem classes as well as a method to execute their methods according to a defined logic.

public class Facade {
    private SubsystemClass1 subsystemClass1;
    private SubsystemClass2 subsystemClass2;

    public Facade(
        SubsystemClass1 subsystemClass1,
        SubsystemClass2 subsystemClass2
    ) {
        this.subsystemClass1 = subsystemClass1;
        this.subsystemClass2 = subsystemClass2;
    }

    public void subsystemOperation() {
        this.subsystemClass1.operationOne();
        this.subsystemClass2.operationTwo();
    }
}

And that is it already. The main construct of the Facade Pattern consists of these four Java files. The only thing that remains is to apply their logic within the executing main class. The main(...) method creates an instance of the SubsystemClass1 and SubsystemClass2. There also is another instance for the Facade that takes the instances of the subsystem classes as parameters. After that the subsystemOperation() method is executed, leading to prints to the command line interface.

public class Main {
    public static void main(String[] args) {
        System.out.println("Facade Pattern in Java");
        System.out.println("----------------------");
        System.out.println();
        
        // Create subsystem classes.
        SubsystemClass1 subsystemClass1 = new SubsystemClass1();
        SubsystemClass2 subsystemClass2 = new SubsystemClass2();

        // Create facade.
        Facade facade = new Facade(subsystemClass1, subsystemClass2);

        // Execute facade operation.
        facade.subsystemOperation();
    }
}

There also needs to be a Manifest.txt file within the same folder. This is a metadata file used primarily in JAR files. It contains information about the JAR file itself and its contents. It is placed within thie META-INF folder within the JAR archive file structure.

Main-Class: Main

To compile this code into an executable Java application which would be a JAR file, a couple of commands need to be executed from within the same directory. The commands are found within the build file.

build.cmd (Windows)
@echo off

javac *.java
jar cvfm FacadeDemo.jar Manifest.txt *.class
build (MacOS / Linux)
#!/bin/bash

javac *.java
jar cvfm FacadeDemo.jar Manifest.txt *.class

Now that the compilation has taken place, there are new files within the same directory. Every JAVA file has its equivalent CLASS file, and there is also a file called FacadeDemo.jar. This is the Java application that needs to be executed. The command for that is within the run file.

run.cmd (Windows)
@echo off

java -jar FacadeDemo.jar
run (MacOS / Linux)
#!/bin/bash

java -jar FacadeDemo.jar

Testing the Java Example

Now that all the files are ready and within their correct location they can be put to test. First we need to compile the Java code and then we can execute it to see what it will print in the Windows Command Prompt or in the MacOS / Linux Terminal.

build.cmd (Windows)

build.cmd (Windows)

build (MacOS / Linux)

build (MacOS / Linux)

run.cmd (Windows)

run.cmd (Windows)

run (MacOS / Linux)

run (MacOS / Linux)

Python Example

The following example is a Python application putting the Facade Pattern into action. All the following files need to be placed into the same folder so that the code within the files can work properly, because the files also reference each other. As this is the smallest possible example, this little project consists of four Python files:

  1. subsystem_class_1.py
  2. subsystem_class_2.py
  3. facade.py
  4. main.py

For this example to work the first thing to do is create subsystem classes having methodes that do something. In our case we create the SubsystemClass1 that has a method operationOne() and SubsystemClass2 that has a method operationTwo().

class SubsystemClass1:
    def operationOne():
        print("Subsystem class 1 calls operation one.")
class SubsystemClass2:
    def operationTwo():
        print("Subsystem class 2 calls operation two.")

The next thing is to create the Facade class that holds references to instances of the subsystem classes as well as a method to execute their methods according to a defined logic.

class Facade:
    def __init__(self, subsystemClass1, subsystemClass2):
        self._subsystemClass1 = subsystemClass1
        self._subsystemClass2 = subsystemClass2

    def subsystemOperation(self):
        self._subsystemClass1.operationOne()
        self._subsystemClass2.operationTwo()

And that is it already. The main construct of the Facade Pattern consists of these four Python files. The only thing that remains is to apply their logic within the executing main class. The main() method creates an instance of the SubsystemClass1 and SubsystemClass2. There also is another instance for the Facade that takes the instances of the subsystem classes as parameters. After that the subsystemOperation() method is executed, leading to prints to the command line interface.

from subsystem_class_1 import SubsystemClass1
from subsystem_class_2 import SubsystemClass2
from facade import Facade

def main():
    print("Facade Pattern in Python")
    print("------------------------")
    print()

    # Create subsystem classes.
    subsystemClass1 = SubsystemClass1
    subsystemClass2 = SubsystemClass2

    # Create facade.
    facade = Facade(subsystemClass1, subsystemClass2)

    # Execute facade operation.
    facade.subsystemOperation()

if __name__ == "__main__":
    main()

There is no need to compile anything in Python. The code is executed directly using the python command under Windows and the python3 command under MacOS / Linux.

run.cmd (Windows)
@echo off

python main.py
run (MacOS / Linux)
#!/bin/bash

python3 main.py

Testing the Python Example

Now that all the files are ready and within their correct location they can be put to test. Python does not need to be compiled before being run. Therefore we can execute it right away to see what it will print in the Windows Command Prompt or in the MacOS / Linux Terminal.

run.cmd (Windows)

run.cmd (Windows)

run (MacOS / Linux)

run (MacOS / Linux)

More Information

So, where do I have my information from? In general, there are lots of places on the internet that offer great information. But that is just one source of information. Another source would be books. Those have the advantage that usually several people work on the same book before it is released, raising the chance for distribution of good and proven information.

Head First - Design Patterns

Building Extensible and Maintainable Object-Oriented Software

A book that has proven to be a valuable asset within my personal library is Head First - Design Patterns by the publisher O'Reilly. It has a fun approach to this topic, having recurring characters, such as the Guru, the Developer, the Skeptical Developer, Joe, and many more.

Java Design Patterns

A Hands-On Experience with Real-World Examples

Another highly valuable book is Java Design Patterns: A Hands-On Experience with Real-World Examples by the publisher Apress. It offers a conservative and rather scientific approach to the subject. It also offers code examples in Java, although any object-oriented programming language applies to the design patterns shown here.

We use cookies

We deeply value your privacy and want to ensure you have the best possible experience on our website. By accepting our Cookie Consent, you're helping us tailor your visit to your preferences, providing you with personalized content and ensuring that all features work seamlessly.

However, if you choose not to accept our Cookie Consent, some parts of the website may not function optimally. We want you to enjoy full access to all the great content and features we offer, so we encourage you to consider accepting our Cookie Consent.

Please be aware that even if you choose not to accept our Cookie Consent, you can still browse our website. However, some functionalities may be limited, and you may not experience the website to its fullest potential.

For more details on how we handle your data, please refer to our Privacy Policy.