Also known as Handle/Body.
Note : When there is only one fixed implementation - also known as Pimpl.
Decouple an abstraction from its implementation so that the two can vary independently.
It lets you split a large class into two separate hierarchies :
- Abstraction
- Implementation Which can be developed independently.
You should use the Bridge pattern in the following cases :
- The class (abstraction) and what it does (implementation) both vary often.
- You want to extend a class in several independent dimensions.
- You want to select an implementation at runtime (Need to avoid a compile-time binding between the abstraction and its implementation).
- Both abstraction and implementation should be opened to subclassing.
- You want to completely hide the implementation of the abstraction to the client.
- You want to share an implementation among multiple objects while hiding it to the client.
Participants
- Abstraction :
- The abstraction interface.
- It will maintain a reference to an Implementor.
- RefinedAbstraction : An extension to the Abstraction interface.
- Implementator :
- The interface for implementation classes.
- Provide implementation classes with primitive operations.
- ConcreteImplementator : Implements the Implementator interface and defines its concrete implementation.
Note : The Abstraction will forward the client requests to its Implementator object.
How to implement
- Identify the orthogonal dimensions of your class.
- Put the operations the client needs in the Abstraction class. Provide this Abstraction with a reference of the Implementator.
- Determine the operations availables on every plateforms and declare them in the RefinedAbstraction interface.
- Create ConcreteImplementators for every plateform.
Note : In case you have several variants of high-level logic, create RefinedAbstractions for each one of them.
Note : UML class diagram taken from here
Pros
- Allows you to create plateforme independent apps.
- The client code works with high-level abstractions and is not exposed to implementation details.
- Open/Closed principle : Easy to introduce new abstractions and implementations independently of the existing ones.
- Single responsability principle: Separate high-level logic from details.
Cons
- Can produce a complicated code if you are dealing with a highly cohesive class.
Here are some usefull ressources :
- An interesting article on Refactoring guru
- A complete example on bogotobogo
- A complete course on Udemy