DEV Community

Vishnu KN
Vishnu KN

Posted on

TIL: Facade Design Pattern

The Facade design pattern comes in handy when your code is complex and you are dealing with a lot of sub-systems and "wheels within wheels" in your code. It provides a way of navigating all this by creating an interface which takes in the request and behind the scenes, sets the relevant wheels in motion, talks to the relevant sub-systems and delivers the request.

Imagine a large car manufacturing factory. Inside the factory, there are specialized departments which work on specialized aspects of building a car. There might be a chassis department, engine department, paint shop, interior department, quality control department etc. If, as a customer, you tried to co-ordinate with each of these departments to get the car built, it would be a nightmare. To prevent this problem, the factory has a manager or a front-office. All that the customer has to do is to walk in and state his requirement "I want a red sedan with leather seats." and the manager/front-office sets the relevant departments in motion at the right times and delivers on the request.

Code example

// Subsystems (Departments inside the factory)

class ChassisDepartment {
  buildChassis(type) {
    console.log(`πŸ”© Building a ${type} chassis...`);
  }
}

class EngineDepartment {
  installEngine(engineType) {
    console.log(`βš™οΈ Installing a ${engineType} engine...`);
  }
}

class PaintDepartment {
  paint(color) {
    console.log(`🎨 Painting the car ${color}...`);
  }
}

class InteriorDepartment {
  installInterior(interiorType) {
    console.log(`πŸͺ‘ Installing ${interiorType} interior...`);
  }
}

class QualityControlDepartment {
  inspect() {
    console.log(`πŸ§ͺ Performing final inspection...`);
  }
}

// πŸ§‘β€πŸ’Ό Facade (Front Office)/Manager
class CarFactoryFacade {
  constructor() {
    this.chassis = new ChassisDepartment();
    this.engine = new EngineDepartment();
    this.paint = new PaintDepartment();
    this.interior = new InteriorDepartment();
    this.qc = new QualityControlDepartment();
  }

  // High-level method that hides the complexity
  orderCar({ type, engine, color, interior }) {
    console.log("πŸ“‹ Order received at Front Office. Processing...\n");

    this.chassis.buildChassis(type);
    this.engine.installEngine(engine);
    this.paint.paint(color);
    this.interior.installInterior(interior);
    this.qc.inspect();

    console.log(`\nπŸš— Your ${color} ${type} with a ${engine} engine and ${interior} interior is ready!`);
  }
}

// πŸ‘¨β€πŸ’» Client code
const frontOffice = new CarFactoryFacade();

// The client just places an order β€” doesn't deal with each department individually
frontOffice.orderCar({
  type: "Sedan",
  engine: "V8",
  color: "Red",
  interior: "leather"
});

Enter fullscreen mode Exit fullscreen mode

Top comments (0)