DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Facade Pattern in javascript

The Facade Pattern is a structural design pattern that provides a simplified interface to a set of interfaces in a subsystem. It hides the complexities of the subsystem and provides a higher-level interface that makes it easier to use. In JavaScript, the Facade Pattern can be implemented using functions or classes to simplify interactions with a complex system.

Here's a simple example of the Facade Pattern in JavaScript:

// Complex subsystem
class SubsystemA {
  operationA() {
    return "SubsystemA: operationA";
  }
}

class SubsystemB {
  operationB() {
    return "SubsystemB: operationB";
  }
}

class SubsystemC {
  operationC() {
    return "SubsystemC: operationC";
  }
}

// Facade
class Facade {
  constructor() {
    this.subsystemA = new SubsystemA();
    this.subsystemB = new SubsystemB();
    this.subsystemC = new SubsystemC();
  }

  operation() {
    let result = "Facade: ";
    result += this.subsystemA.operationA();
    result += " | " + this.subsystemB.operationB();
    result += " | " + this.subsystemC.operationC();
    return result;
  }
}

// Usage
const facade = new Facade();
console.log(facade.operation());
// Output: Facade: SubsystemA: operationA | SubsystemB: operationB | SubsystemC: operationC

Enter fullscreen mode Exit fullscreen mode

In this example:

SubsystemA, SubsystemB, and SubsystemC represent different parts of a complex system.
The Facade class aggregates instances of the subsystems and provides a higher-level interface called operation that simplifies interactions with the subsystems.
The client code interacts with the Facade to perform operations without needing to understand the complexities of the individual subsystems.
The Facade Pattern is particularly useful when dealing with large and complex systems, providing a clear and simple interface for clients while encapsulating the details of the subsystems. This promotes loose coupling and makes the system more maintainable and easier to understand.

Top comments (0)