Dhananjay Patel Logo
  1. Home
  2. / Blog
  3. / Design Pattern
  4. / Lessons
  5. / 5

Next

Facade Pattern

The Facade pattern provides a simplified interface to a complex subsystem. It reduces the complexity of the system by hiding the underlying implementation details.

When to Use:

Use the Facade pattern when you want to simplify the interface to a complex system.

Example

// Subsystem classes
class CPU {
freeze() {
console.log('CPU freezing...');
}
jump(position: number) {
console.log(`CPU jumping to position ${position}`);
}
execute() {
console.log('CPU executing...');
}
}
class Memory {
load(position: number, data: string) {
console.log(`Memory loading data at position ${position}`);
}
}
class HardDrive {
read(lba: number, size: number) {
return 'Some data from HardDrive';
}
}
// Facade class
class ComputerFacade {
private cpu: CPU;
private memory: Memory;
private hardDrive: HardDrive;
constructor() {
this.cpu = new CPU();
this.memory = new Memory();
this.hardDrive = new HardDrive();
}
start() {
this.cpu.freeze();
this.memory.load(0, this.hardDrive.read(0, 4096));
this.cpu.jump(0);
this.cpu.execute();
}
}
// Usage
const computer = new ComputerFacade();
computer.start();

Pros:

  • Simplifies the interface to complex subsystems.
  • Promotes loose coupling between clients and subsystems.

Cons:

  • Can lead to the creation of overly simple interfaces that don’t offer enough flexibility.
  • May increase the complexity of the system if not used judiciously.

Next