Facade Design Pattern in Java

Facade Design Pattern in Java with Examples

In this article, I am going to discuss Facade Design Pattern in Java with Examples. Please read our previous article where we discussed Proxy Design Pattern in Java with Examples. The Facade Design Pattern falls under the category of the Structural Design Pattern. In this article, we will explore the Facade Pattern, its advantages, disadvantages, and practical applications in software development.

What is Facade Design Pattern?

In software development, complex systems often consist of multiple subsystems and components with intricate interactions. Managing and utilizing these systems efficiently can be challenging. The Facade design pattern provides a simple interface that encapsulates the complexity of the underlying subsystems, making it easier for clients to interact with the system.

The Facade design pattern aims to simplify the usage and understanding of a complex system by providing a unified and simplified interface. It acts as a higher-level abstraction that encapsulates the underlying subsystems and presents a simplified interface to the clients.

As per the GOF definition, Facade Design Pattern states that you need to provide a unified interface to a set of interfaces in a subsystem. The Facade Design Pattern defines a higher-level interface that makes the subsystem easier to use.

In simple words, we can say that the Facade Design Pattern is used to hide the complexities of a system and provides an easy-to-use interface to the client using which the client can access the system. The Facade (usually a wrapper) class sits on the top of a group of subsystems and allows them to communicate in a unified manner.

Understanding the Class or UML Diagram of Facade Design Pattern:

Let us understand the class diagram (or UML Diagram) and understand the different components involved in the Facade Design Pattern. In order to understand the Facade Design Pattern class diagram, please have a look at the following image.

Understanding the Class or UML Diagram of Facade Design Pattern

As shown in the above image, there are three classes involved in the Facade Design Pattern. They are as follows:

  • Facade: The Facade is the central class or component that provides a simplified interface to clients. It encapsulates the complex interactions and dependencies of the underlying subsystems.
  • Subsystems: Subsystems are the individual components or classes that make up the complex system. They contain the implementation details and perform specific tasks within the system.
  • Client: The Client Class uses the Façade Class to access the subsystems.
Example to Understand Facade Design Pattern in Java

Let’s consider a real-world example where the Facade pattern can be applied: an electronics shop. The Facade pattern can be used to create a simplified interface for the shop. The Facade class will act as a single-entry point that encapsulates the complexities of interacting with the subsystems. It will provide high-level methods or operations that coordinate and interact with the underlying subsystems to fulfill customer orders.

By using the Facade pattern, the shop can achieve several benefits. Firstly, it simplifies the interaction between clients and the system, providing a unified and easy-to-use interface. Clients don’t need to understand the intricacies of each subsystem but can rely on the Facade to handle the interactions. Secondly, it encapsulates the complexities and changes within the subsystems, reducing the impact of changes on client code. Additionally, the pattern enhances code maintainability and modularity by promoting loose coupling between the subsystems and the clients. The UML Diagram of this example is given below using Facade Design Pattern.

Example to Understand Facade Design Pattern in Java

Implementing Facade Design Pattern in Java

Step 1: Create a new directory to store all the class files of this project.

Step 2: Open VS Code and create a new project, called Facade.

Step 3: In the project, create a new file called ElectronicsDevice.java. Add the following code to the file:

Implementing Facade Design Pattern in Java

This is the interface from which other concrete classes will be created.

Step 4: In the project, create a new file called Fridge.java. Add the following code to the file:

Facade Design Pattern in Java

Step 5: In the project, create a new file called WashingMachine.java. Add the following code to the file:

Facade Design Pattern in Java with Examples

Step 6: In the project, create a new file called TV.java. Add the following code to the file:

Facade Pattern in Java

Step 7: In the project, create a new file called ElectronicShop.java. Add the following code to the file:

Facade Pattern in Java with Examples

This class will be called whenever a sale is to be made.

Step 8: In the project, create a new file called FacadePatternDemo.java. This class will contain the main() function.

Step 9: Import the following packages into FacadePatternDemo.java:

What is Facade Design Pattern?

Step 10: Write the main() function in FacadePatternDemo.java:

Example to Understand Facade Design Pattern in Java

In the main function, the user is asked for their choice of device. Based on this user input, we “sell” the device to the user.

Step 11: Compile and execute the application. Ensure compilation is successful. Verify that the program works as expected.

Example to Understand Facade Design Pattern

Congratulations! You now know how to implement facade patterns!

UML Diagram of Facade Design Pattern:

Now, let us see the Facade Design Pattern UML Diagram Components with our Example so that you can easily understand the UML Diagram.

UML Diagram of Facade Design Pattern

The classes can be described as follows:

  1. Object: This is the interface that provides the basic function definitions for each object.
  2. ConcreteObject: This is the class that implements the functions defined in the aforementioned interface.
  3. Handler: This class acts as the middleman between the driver class and the objects.
  4. DriverClass: This class contains the main() function and is responsible for simulating the application.
The Complete Example Code of Facade Design Pattern in Java
ElectronicsDevice.java
public interface ElectronicsDevice
{
    public String deviceName();
    public int price();
    public String modelNo();
}
ElectronicsShop.java
public class ElectronicShop
{
    private ElectronicsDevice fridge, washingMachine, tv;
    
    public ElectronicShop()
    {
        fridge = new Fridge();
        washingMachine = new WashingMachine();
        tv = new TV();
    }

    public void sellFridge()
    {
        System.out.println("Details of " + fridge.deviceName() + " :");
        System.out.println("Model No: " + fridge.modelNo());
        System.out.println("Price: Rs. " + fridge.price());
    }

    public void sellWashingMachine()
    {
        System.out.println("Details of " + washingMachine.deviceName() + " :");
        System.out.println("Model No: " + washingMachine.modelNo());
        System.out.println("Price: Rs. " + washingMachine.price());
    }

    public void sellTV()
    {
        System.out.println("Details of " + tv.deviceName() + " :");
        System.out.println("Model No: " + tv.modelNo());
        System.out.println("Price: Rs. " + tv.price());
    }
}
FacadePatternDemo.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class FacadePatternDemo
{
    public static void main(String[] args) throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        ElectronicShop shop = new ElectronicShop();

        System.out.println();
        System.out.println("Buy a device: ");
        System.out.println("1. Fridge");
        System.out.println("2. Washing Machine");
        System.out.println("3. TV");
        System.out.println();
        System.out.print("Enter your choice here: ");

        int choice = Integer.parseInt(br.readLine());

        if (choice == 1)        shop.sellFridge();
        else if (choice == 2)   shop.sellWashingMachine();
        else if (choice == 3)   shop.sellTV();
        else                    System.out.println("Wrong choice!");
    }    
}
Fridge.java
public class Fridge implements ElectronicsDevice
{
    @Override
    public String deviceName()  {return "LG Fridge";}

    @Override
    public int price()          {return 50000;}

    @Override
    public String modelNo()     {return "ABC123";}
}
TV.java
public class TV implements ElectronicsDevice
{
    @Override
    public String deviceName()  {return "Sony Bravia 85\"";}

    @Override
    public int price()          {return 700000;}

    @Override
    public String modelNo()     {return "GHI789";}
}
WashingMachine.java
public class WashingMachine implements ElectronicsDevice
{
    @Override
    public String deviceName()  {return "Samsung Washing Machine";}

    @Override
    public int price()          {return 24000;}

    @Override
    public String modelNo()     {return "DEF456";}
}
Advantages of the Facade Design Pattern in Java:

Some of the Advantages of using the Facade Design Pattern in Java are as follows:

  • Simplified Interface: The primary advantage of the Facade pattern is the provision of a simplified interface for clients. It abstracts away the complexity of the underlying subsystems and presents a more intuitive and straightforward interface, reducing the learning curve and making it easier to use.
  • Encapsulation of Complexity: The Facade pattern encapsulates the complex interactions and dependencies of the subsystems within a single component. This encapsulation shields the clients from the complexity and intricacies of the underlying system, promoting loose coupling and separation of concerns.
  • Improved Maintainability: The Facade pattern enhances code maintainability by providing a centralized point for managing the interactions with the subsystems. Changes or updates to the underlying subsystems can be confined within the Facade, ensuring that clients are shielded from the impact of those changes. This simplifies maintenance and reduces the risk of introducing bugs or breaking client code.
  • Increased Reusability: The Facade pattern promotes reusability by providing a standardized and simplified interface to the complex system. Clients can rely on the Facade without needing to understand the intricate details of the subsystems, facilitating code reuse across different parts of the application or even in different applications.
  • Improved Performance: In certain scenarios, the Facade pattern can also improve performance. By encapsulating complex interactions into higher-level abstractions, the Facade can optimize and streamline the interactions between subsystems, leading to more efficient execution and reduced overhead.
Disadvantages of the Facade Design Pattern in Java:

Some of the Disadvantages of using the Facade Design Pattern in Java are as follows:

  • Limited Flexibility: One potential disadvantage of the Facade pattern is that it may limit flexibility in some cases. Since the Facade provides a simplified interface, it may not expose all the functionalities or customization options available in the underlying subsystems. Clients requiring more fine-grained control or access to specific subsystem features may need to bypass the Facade and interact directly with the subsystems.
  • Increased Dependency on the Facade: Another drawback is that the Facade pattern introduces a dependency between clients and the Facade component. Clients become tightly coupled to the Facade, and any changes or updates to the Facade may impact the client code. This tight coupling can hinder flexibility and make it harder to replace or extend the Facade in the future.
  • Limited Extensibility: The Facade pattern may face limitations when it comes to extending the system with new subsystems or functionalities. Adding new subsystems may require modifications to the Facade, potentially affecting existing client code. This limitation should be considered when designing systems that may undergo frequent expansions or modifications.

The Facade design pattern offers advantages in terms of simplified interface, encapsulation of complexity, improved maintainability, increased reusability, and potentially improved performance. It provides a valuable tool for managing complex systems and simplifying interactions between clients and subsystems.

However, it is crucial to consider the potential drawbacks of the Facade pattern, such as limited flexibility, increased dependency on the Facade, and limited extensibility. By carefully evaluating the specific requirements and constraints of the system, developers can effectively leverage the Facade pattern to simplify complex systems and enhance the maintainability and usability of their applications.

In the next article, I am going to discuss Adapter Design Pattern in Java with Examples. Here, in this article, I try to explain Facade Design Pattern in Java with Examples. I hope you understood the need for and use of the Facade Design Pattern in Java.

Leave a Reply

Your email address will not be published. Required fields are marked *