design-patterns/structural/facade
2020-09-27 14:26:34 +02:00
..
__init__.py add facade code example 2020-09-27 14:26:34 +02:00
facade.py add facade code example 2020-09-27 14:26:34 +02:00
main.py add facade code example 2020-09-27 14:26:34 +02:00
README.md add facade code example 2020-09-27 14:26:34 +02:00
subsystems.py add facade code example 2020-09-27 14:26:34 +02:00

Facade Pattern

Facade is a structural design pattern that provides a simplified (but limited) interface to a complex system of classes, library or framework.

Summary

Facade is a structural design pattern that provides a simplified interface to a library, a framework, or any other complex set of classes.

Problem

Imagine that you must make your code work with a broad set of objects that belong to a sophisticated library or framework. Ordinarily, youd 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.

Having a facade is handy when you need to integrate your app with a sophisticated library that has dozens of features, but you just need a tiny bit of its functionality.

For instance, an app that uploads short funny videos with cats to social media could potentially use a professional video conversion library. However, all that it really needs is a class with the single method encode(filename, format). After creating such a class and connecting it with the video conversion library, youll have your first facade.

How to Implement

  1. Check whether its possible to provide a simpler interface than what an existing subsystem already provides. Youre on the right track if this interface makes the client code independent from many of the subsystems classes.

  2. Declare and implement this interface in a new facade class. The facade should redirect the calls from the client code to appropriate objects of the subsystem. The facade should be responsible for initializing the subsystem and managing its further life cycle unless the client code already does this.

  3. To get the full benefit from the pattern, make all the client code communicate with the subsystem only via the facade. Now the client code is protected from any changes in the subsystem code. For example, when a subsystem gets upgraded to a new version, you will only need to modify the code in the facade.

  4. If the facade becomes too big, consider extracting part of its behavior to a new, refined facade class