Overview
The Facade Design Pattern provides a simplified interface to a larger body of code, such as a complex subsystem. It is a structural design pattern that aims to reduce the complexity of interactions between multiple classes or components.
Key Characteristics
- Provides a unified and simplified interface to a set of interfaces in a subsystem.
- Promotes loose coupling between subsystems and their clients.
- Hides the complexities of the subsystem from the client.
Implementation
The following is an example of a Facade implementation in Java:
// Subsystem classes
class SubsystemA {
public void operationA() {
System.out.println("Subsystem A: Operation A");
}
}
class SubsystemB {
public void operationB() {
System.out.println("Subsystem B: Operation B");
}
}
class SubsystemC {
public void operationC() {
System.out.println("Subsystem C: Operation C");
}
}
// Facade class
class Facade {
private SubsystemA subsystemA;
private SubsystemB subsystemB;
private SubsystemC subsystemC;
public Facade() {
this.subsystemA = new SubsystemA();
this.subsystemB = new SubsystemB();
this.subsystemC = new SubsystemC();
}
public void operation1() {
System.out.println("Facade: Operation 1");
subsystemA.operationA();
subsystemB.operationB();
}
public void operation2() {
System.out.println("Facade: Operation 2");
subsystemB.operationB();
subsystemC.operationC();
}
}
// Demo
public class FacadeDemo {
public static void main(String[] args) {
Facade facade = new Facade();
facade.operation1();
facade.operation2();
}
}
When to Use
- When you want to provide a simplified interface to a complex subsystem.
- When there are many dependencies between clients and subsystems.
- When you want to layer your system into subsystems to minimize interdependencies.
Advantages
- Reduces the complexity of the client by hiding the subsystem's implementation details.
- Improves code readability and maintainability.
- Promotes loose coupling between subsystems and their clients.
Disadvantages
- Can introduce a single point of failure if the Facade is overly complex or critical.
- May limit the flexibility of clients who need to use specific subsystem features.