Everything you just saw in this article is only a small part of the book Introduction to design patterns, the most complete book of design patterns in Spanish, we cover 25 design patterns along with 25 real-world projects. Forget about learning design patterns with typical Internet examples of how to make pizza, animals, and geometric shapes. I invite you to see my book:See book
The Bridge design pattern is used for decoupling an abstraction from its implementation, the purpose is that each one can be modified separately without affecting the other; in other words, an abstraction gets decoupled from its implementation so they can vary independently.
The Bridge pattern is mostly used when we have two related pieces of software and there’s a high probability that modifying one of them can lead to have the other modified too. What Bridge proposes to solve this problem is creating a class structure based on aggregation, which includes a bridge class for decoupling the class we want to use from the client, so the latter can’t be aware of the former, in a way that one can change without affecting the other.
The components of this pattern are:
- Abstraction: Interface for defining the structure of the bridge class.
- AbstractionImpl: Class used as a bridge for decoupling Abstraction from Implementor. This class inherits from Abstraction.
- Implementor: It defines a common class structure for all the ConcreteImplementor. This interface isn’t strictly required for implementing the pattern.
- ConcreteImplementor: Class group which inherits from Implementor and is subject to changes, the reason why we are using the Bridge design pattern.
- The client executes an AbstraccionImploperation.
- AbstraccionImpl relays this petition to ConcreteImplementor, at this point AbstraccionImpl can convert the parameters needed for executing the ConcreteImplementor.
- ConcreteImplementor returns the results to AbstraccionImpl.
- The AbstraccionImpl converts the results coming from ConcreteImplementor to give them to the client.
By implementing the Bridge we are going to create an application that allows us to communicate with an external system, this communication must by encrypted using different algorithms. However, the concrete implementation of the encryption algorithm may change, which means that we need to create an adapter for decoupling this concrete implementation from the handling method, which is why we will use an adapter for encapsulating the inner logic and to provide a single interface for all the encryption methods.