Bridge#
The Bridge design pattern is a structural pattern that decouples an abstraction from its implementation so that the two can vary independently. This pattern is useful when you want to avoid a permanent binding between an abstraction and its implementation.
Imagine you have a remote control that can turn on and off different devices, such as a TV or a radio. The Bridge pattern allows you to separate the remote control from the devices it controls, so you can add new devices without changing the remote control.
Key Concepts#
Abstraction: The high-level control layer for some entity.
Implementor: The low-level layer that performs the actual work.
Concrete Implementor: A specific implementation of the Implementor interface.
Refined Abstraction: Extends the interface defined by Abstraction.
Benefits#
Decoupling Abstraction and Implementation: It separates the abstraction from its implementation, allowing both to vary independently. This makes the code more flexible and easier to maintain.
Improved Extensibility: You can extend both the abstraction and the implementation hierarchies independently without affecting each other. This makes it easier to introduce new abstractions and implementations.
Enhanced Modularity: By separating concerns, the Bridge pattern promotes a cleaner and more modular codebase. Each class has a single responsibility, adhering to the Single Responsibility Principle.
Reduced Code Duplication: Common code can be placed in the abstraction, while specific implementations can be handled by the implementor classes. This reduces redundancy and promotes code reuse.
Increased Flexibility: The pattern allows you to switch implementations at runtime, providing greater flexibility in how objects are used and interact.
Simplified Testing: Decoupling makes it easier to test components in isolation. You can mock or stub implementations when testing the abstraction, and vice versa.
These benefits make the Bridge pattern a powerful tool for managing complexity in large and evolving codebases. UML Diagram ———–
+-------------------+ +----------------------+
| Abstraction | | Implementor |
+-------------------+ +----------------------+
| - implementor: |<>------->| + operationImpl() |
| Implementor | +----------------------+
| + operation() | | |
+-------------------+ +----------------------+
/ \ / \
/ \ / \
/ \ / \
+-------------------+ +----------------------+
|Refined Abstraction| | Concrete Implementor |
+-------------------+ +----------------------+
| + operation() | | + operationImpl() |
+-------------------+ +----------------------+
--- Python Example ---