Bridge: separate two changing dimensions
Picture
Basic and advanced remotes can control speakers or screens. Subclassing every pair makes combinations multiply.
Predict
Do five remotes and four devices require twenty combined subclasses?
Walk through the small example
No. One device contract lets the two axes combine.
Mental model and complete Python solution
Remote holds a device rather than inheriting from it. AdvancedRemote adds mute without a speaker-specific or screen-specific subtype. Implementations must honestly support the promised capability; a device without volume should use a different contract rather than silently pretending to mute.
What the function promises: Local device objects support power and volume 0..100. No physical device is controlled.
class Device:
def __init__(self):
self.on, self.volume = False, 50
def power(self, enabled):
self.on = bool(enabled)
def set_volume(self, value):
if not 0 <= value <= 100:
raise ValueError("Invalid volume")
self.volume = value
class Screen:
def __init__(self):
self.settings = {"power": False, "volume": 50}
def power(self, enabled):
self.settings["power"] = bool(enabled)
def set_volume(self, value):
if not 0 <= value <= 100:
raise ValueError("Invalid volume")
self.settings["volume"] = value
class Remote:
def __init__(self, device):
self.device = device
def turn_on(self):
self.device.power(True)
class AdvancedRemote(Remote):
def mute(self):
self.device.set_volume(0)
speaker, screen = Device(), Screen()
AdvancedRemote(speaker).mute()
Remote(screen).turn_on()
assert speaker.volume == 0 and screen.settings["power"]
AdvancedRemote(screen).mute()
assert screen.settings["volume"] == 0
Work and storage: O(1) delegation overhead.
When to recognize it: An adapter translates an incompatible existing interface. A bridge separates two changing dimensions in the design itself.
Check before applying it: Independent dimensions still require truthful shared capabilities.
Change one rule
A device has no meaningful volume control. Should set_volume silently do nothing?
See what changes
No, if callers depend on muting. Split capabilities or choose another abstraction so the behavioral contract remains truthful.
Connect
Let small objects work together: Compose independent dimensions instead of subclassing every combination.
Adapter: translate a boundary: Distinguish planned independent variation from adapting an existing mismatch.