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"
});
Top comments (0)