Facade

Provides a simplified interface to a library, a framework, or any other complex set of classes.

classDiagram
    class Client {
        +operation()
    }
    class Facade {
        -Subsystem1 sub1
        -Subsystem2 sub2
        +operation()
    }
    class Subsystem1 {
        +operation1()
        +operationN()
    }
    class Subsystem2 {
        +operation1()
        +operationZ()
    }

    Client --> Facade
    Facade --> Subsystem1
    Facade --> Subsystem2

When to use

Use the Facade pattern when you need to have a limited but straightforward interface to a complex subsystem. Use when you want to structure a subsystem into layers.

Explanation

Problem

Imagine that you must make your code work with a broad set of objects that belong to a sophisticated library or framework. Normally, you’d need to initialize all of those objects, keep track of dependencies, execute methods in the correct order, and so on. As a result, the business logic of your classes would become tightly coupled to the implementation details of 3rd-party classes, making it hard to comprehend and maintain.

Solution

A facade is a class that provides a simple interface to a complex subsystem which contains lots of moving parts. A facade might provide limited functionality in comparison to working with the subsystem directly. However, it includes only those features that clients really care about.

Real world problem

  1. Phone Support: You call a support center (Facade). The operator talks to Logistics, Billing, and Technical departments for you.
  2. Video Converter: Converting a video involves bitrates, codecs, audio buffers. A Facade allows convert(filename, "mp4").
  3. Wallet API: A simple sendMoney() method might involve checking balance, verifying security, logging transaction, and notifying the bank.

Pros and Cons

Pros Cons
- Isolation: You can isolate your code from the complexity of a subsystem. - God Object: A facade can become a god object coupled to all classes of an app.

Comparison

  • Adapter: Facade defines a new interface for existing objects. Adapter tries to make the existing interface usable.
  • Abstract Factory: Abstract Factory can serve as an alternative to Facade when you only want to hide the way the subsystem objects are created.
  • Mediator: Mediator’s main goal is to eliminate mutual dependencies between system components. Facade defines a simplified interface to a subsystem of objects, but it doesn’t introduce any new functionality.

Code example

Typescript

Php