Felix - 06.02.2023

The Facade Pattern

Created this little presentation for work and gona share it here!

The Facade Pattern is a structural design pattern that helps to simplify and hide the complexity of a system behind a simple and easy to understand interface.

Example

Complex module structure

class Motor {
    public start() {
        console.log('Motor started');
    }
}

class Ignition {
    public ignite(motor: Motor) {
        console.log('Ignition started');
        motor.start();
    }
}

class Wheels {
    public rotate(kmPerHour: number) {
        console.log(`Wheels rotated at ${kmPerHour} km/h`);
    }
}

class WindowSwiper {
    public swipe() {
        console.log('Window swiped');
    }
}

This is an example of a complex system.

Implementation without a Facade

const motor: Motor = new Motor();
const ignition: Ignition = new Ignition();
const wheels: Wheels = new Wheels();
const windowSwiper: WindowSwiper = new WindowSwiper();


ignition.ignite(motor);
let kmPerHour = 100;
wheels.rotate(kmPerHour);
windowSwiper.swipe();

The implementation of the complex system is very hard to understand and the client needs to know the inner workings of the system. This can lead to spaghetti code and makes the system hard to maintain.

Creating a Facade

export class Car {

    private motor: Motor;
    private ignition: Ignition;
    private wheels: Wheels;
    private windowSwiper: WindowSwiper;

    constructor() {
        this.motor = new Motor();
        this.ignition = new Ignition();
        this.wheels = new Wheels();
        this.windowSwiper = new WindowSwiper();
    }

    public drive(kmPerHour: number, isRaining?: boolean) {
        this.ignition.ignite(this.motor);
        this.wheels.rotate(kmPerHour);
        if (isRaining) {
            this.windowSwiper.swipe();
        }
    }

}

The Facade hides the complexity of the system and provides a simple interface to the client.

The functionality is the same as the implementation without a Facade but the code is much easier to understand.

Implementation with Facade

const car = new Car();
car.drive(80, true);

The implementation of the complex system is now much easier and the client does not need to know the inner workings of the system.

Negatives

The facade pattern can lead to a Black Box Problem. The user of the facade does not know what is happening inside the module, which makes it harder to debug and maintain.

Use Cases

A good use-case for this pattern is a system that is used by multiple clients.

  • Node Modules
  • Microservices
  • APIs