Facade Pattern

Category : Design Patterns | Sub Category : Structural design patterns | By Prasad Bonam Last updated: 2023-07-09 14:32:31 Viewed : 70

Facade Pattern

The Facade pattern is a structural design pattern that provides a simplified interface to a complex system or a set of interfaces. It hides the complexity of the underlying subsystem and provides a single entry point for the client to interact with the system. The Facade pattern promotes loose coupling and encapsulation by providing a higher-level interface that abstracts away the details and dependencies of the subsystem. Here is an example of implementing the Facade pattern in Java:

// Complex subsystem classes class Subsystem1 { public void operation1() { System.out.println("Subsystem1 operation1"); } // Additional methods and operations } class Subsystem2 { public void operation2() { System.out.println("Subsystem2 operation2"); } // Additional methods and operations } class Subsystem3 { public void operation3() { System.out.println("Subsystem3 operation3"); } // Additional methods and operations } // Facade class class Facade { private Subsystem1 subsystem1; private Subsystem2 subsystem2; private Subsystem3 subsystem3; public Facade() { subsystem1 = new Subsystem1(); subsystem2 = new Subsystem2(); subsystem3 = new Subsystem3(); } public void operation() { subsystem1.operation1(); subsystem2.operation2(); subsystem3.operation3(); // Perform additional operations or coordinate the subsystems } } // Client code public class Client { public static void main(String[] args) { Facade facade = new Facade(); facade.operation(); } }

In this example:

  • The Subsystem1, Subsystem2, and Subsystem3 classes represent complex subsystems with their own operations and functionalities.
  • The Facade class acts as a facade or simplified interface to the subsystems. It encapsulates the subsystem objects and provides a higher-level interface that clients can interact with.
  • The Facade class initializes instances of the subsystem classes in its constructor and exposes a single operation() method that coordinates the operations of the subsystems. It may perform additional operations or provide a simplified interface for the clients.
  • The client code in the Client class demonstrates the usage of the facade. It creates an instance of the Facade class and calls its operation() method, which internally invokes the appropriate methods of the subsystem classes.

By using the Facade pattern, you can provide a unified and simplified interface to a complex system or a set of interfaces. It shields the clients from the complexities of the subsystem and promotes loose coupling between the clients and the subsystem. It also enables easier maintenance and modification of the system by isolating the impact of changes within the facade.

Related Articles

Leave a Comment: