Skip to content

Facade Design Pattern

Dean Hristov edited this page Sep 20, 2023 · 1 revision

A Facade is a structural design pattern that provides a simplified interface to a library, a framework, or any other complex set of classes. It acts as a front-facing interface masking more complex or structural code. This pattern hides the complexities of the larger system and provides a simpler interface to the client. It typically involves a single wrapper class that contains a set of members required by the client. These members access the system on behalf of the facade client and hide the implementation details. A simple UML diagram can be seen here or here.

A Great fit when:

The facade pattern is typically used when:

  • A simple interface is required to access a complex system,
  • A system is very complex or difficult to understand,
  • An entry point is needed to each level of layered software or the abstractions and implementations of a subsystem are tightly coupled.

Example:

Subsystem 1

class AlarmSystem {
  activateAlarms(): string {
    return 'Turning on the alarm';
  }

  deactivateAlarms(): string {
    return 'Turning off the alarm';
  }
}

Subsystem 2

class LightSystem {
  turnOnLight(): string {
    return 'Turning on the light';
  }

  turnOffLight(): string {
    return 'Turning off the light';
  }
}

The Facade class

export interface IHouseFacade {
  comingIn(): string;

  goingOut(): string;
}

class HouseFacade implements IHouseFacade {
  private readonly lightSystem: LightSystem;
  private readonly alarmSystem: AlarmSystem;

  constructor() {
    this.lightSystem = new LightSystem();
    this.alarmSystem = new AlarmSystem();
  }

  comingIn(): string {
    this.lightSystem.turnOnLight();
    this.alarmSystem.deactivateAlarms();

    return 'The house is not empty';
  }

  goingOut(): string {
    this.lightSystem.turnOffLight();
    this.alarmSystem.activateAlarms();

    return 'The house is empty';
  }
}
Code in action
const house: HouseFacade = new HouseFacade();

house.comingIn();
house.goingOut();

More info can be found on the wiki page.