Bridge Pattern: Definition, Example, and When to Use
Bridge Pattern is a design pattern that separates an abstraction from its implementation so both can vary independently. It helps to avoid a permanent binding between an abstraction and its implementation, making the system more flexible and easier to extend.How It Works
Imagine you have a remote control for different types of devices like TVs and Radios. Instead of making a separate remote for each device, the Bridge Pattern splits the remote (abstraction) from the device (implementation). This way, you can mix and match any remote with any device without changing their code.
In software, this means you create two separate class hierarchies: one for the abstraction and one for the implementation. The abstraction holds a reference to the implementation and delegates work to it. This separation allows you to change or add new abstractions and implementations independently, making your code easier to maintain and extend.
Example
from abc import ABC, abstractmethod # Implementation interface class Device(ABC): @abstractmethod def turn_on(self): pass @abstractmethod def turn_off(self): pass # Concrete implementations class TV(Device): def turn_on(self): print("TV is now ON") def turn_off(self): print("TV is now OFF") class Radio(Device): def turn_on(self): print("Radio is now ON") def turn_off(self): print("Radio is now OFF") # Abstraction class RemoteControl: def __init__(self, device: Device): self.device = device def turn_on(self): self.device.turn_on() def turn_off(self): self.device.turn_off() # Extended abstraction class AdvancedRemoteControl(RemoteControl): def mute(self): print("Device muted") # Usage remote_tv = RemoteControl(TV()) remote_tv.turn_on() remote_tv.turn_off() remote_radio = AdvancedRemoteControl(Radio()) remote_radio.turn_on() remote_radio.mute() remote_radio.turn_off()
When to Use
Use the Bridge Pattern when you want to avoid a permanent link between an abstraction and its implementation. It is helpful when both the abstraction and implementation may change or grow independently.
For example, if you are building a graphic library that supports multiple shapes (circle, square) and multiple rendering methods (vector, raster), the bridge pattern lets you combine any shape with any rendering method without creating many subclasses.
It is also useful when you want to switch implementations at runtime or when you want to hide implementation details from clients.
Key Points
- Separates abstraction from implementation to allow independent changes.
- Uses composition to link abstraction and implementation.
- Reduces subclass explosion by combining hierarchies.
- Improves flexibility and scalability of code.
- Commonly used in UI toolkits, device drivers, and graphic libraries.