The Facade Pattern

The Facade Pattern is a structural design pattern that provides a simplified interface to a complex subsystem. Instead of interacting with many classes directly, each with its own API, you create a facade class that wraps these subsystems and exposes a single, unified interface.

The key goals of the Facade Pattern is to hide complexity in order to improve code readability and reduce coupling between client code and subsystems.Think of it like a hotel reception desk: instead of calling the chef, cleaners, and manager individually, you just talk to the receptionist.

You can use the Facade Pattern when you have a complicated subsystem with many dependencies, when you want to decouple your code from details of the subsystem or when you want to provide clean, single entry point of for client code.

Example in PHP

The classes that we have to use


class CoffeeMachine {
    public function start() {
        echo "Coffee machine started\n";
    }

    public function brew() {
        echo "Brewing coffee\n";
    }
}

class Grinder {
    public function grindBeans() {
        echo "Grinding coffee beans\n";
    }
}

class WaterHeater {
    public function heat() {
        echo "Heating water\n";
    }
}

                                        

The Facade class


class CoffeeFacade {
    private CoffeeMachine $coffeeMachine;
    private Grinder $grinder;
    private WaterHeater $waterHeater;

    public function __construct(CoffeeMachine $coffeeMachine, Grinder $grinder, WaterHeater $waterHeater) {
        $this->coffeeMachine = $coffeeMachine;
        $this->grinder = $grinder;
        $this->waterHeater = $waterHeater;
    }

    public function makeCoffee() {
        $this->coffeeMachine->start();
        $this->grinder->grindBeans();
        $this->waterHeater->heat();
        $this->coffeeMachine->brew();
        echo "Coffee is ready!\n";
    }
}

                                        

Client code


$coffeeMachine = new CoffeeMachine();
$grinder = new Grinder();
$waterHeater = new WaterHeater();

$coffeeFacade = new CoffeeFacade($coffeeMachine, $grinder, $waterHeater);
$coffeeFacade->makeCoffee();
                                        

The use of the Facade Pattern of the above code it has a simplified interface by just calling the makeCoffee() method instead of juggling with multiple classes. It is loose coupled because the client code has no need to know about the different subsystems and is high maintainable due to the fact that when the coffee making process changes only the facade needs updating.

Facade vs Service

Many times Facade Pattern is confused with the Service Pattern. The main difference is that of purpose of each. The Facade Pattern tries to conceal complex proccess and the Service Pattern encapsulates the business logic. For example a Facade Pattern can be handling the save to disk feature and the Service Pattern will handle wage calculation.