Too Many Subclasses? The Bridge Pattern in Python

This article explains how the Bridge pattern replaces combined subclasses with two hierarchies joined by a reference, how Python's io module applies it, and how it differs from the Adapter and Strategy patterns.

A green tree python coiled in tight loops over a brown branch, with its head resting on the coils against blurred foliage
Photo by Derek Otway on Unsplash

When a class varies along two independent dimensions, inheritance tends to produce one subclass for every combination, so that two kinds of remote control and two kinds of device already require four classes, and each new device adds as many classes as there are remotes. The present article examines the Bridge pattern, which splits such a hierarchy into two, an abstraction and an implementation, and connects them with a reference instead of inheritance. A game whose settings menu lets the player choose the graphics backend provides an appropriate image: the same menus, maps and characters are drawn through whichever renderer is selected, and nobody writes a separate version of the game for each renderer. This means that the abstraction, the part that the rest of the program uses, delegates its work to an implementation object that it receives and that can be replaced without touching it. The analogy, however, stops at this point, because a game usually has to restart to change its renderer, whereas a Python object can receive a different implementation at any moment. Keeping the two dimensions in separate hierarchies, so that their classes add up instead of multiplying, is the secret weapon of this pattern.

Two Hierarchies Instead of One

The class explosion that the Bridge pattern prevents is a matter of arithmetic: with M abstractions and N implementations, inheritance needs M × N subclasses, while a bridge needs M + N classes. The implementation side declares a small set of primitive operations, and the abstraction side builds its higher-level operations on those primitives only. In the following example, the remotes are the abstraction and the devices are the implementation; the device is passed to the constructor of the remote, which is the form of injection described in the article devoted to dependency injection.

from abc import ABC, abstractmethod

class Device(ABC):
    @abstractmethod
    def is_enabled(self): ...

    @abstractmethod
    def set_enabled(self, on): ...

    @abstractmethod
    def get_volume(self): ...

    @abstractmethod
    def set_volume(self, level): ...

class TV(Device):
    def __init__(self):
        self._on, self._volume = False, 30

    def is_enabled(self):
        return self._on

    def set_enabled(self, on):
        self._on = on

    def get_volume(self):
        return self._volume

    def set_volume(self, level):
        self._volume = max(0, min(100, level))

class Radio(Device):
    def __init__(self):
        self._on, self._volume = False, 50

    def is_enabled(self):
        return self._on

    def set_enabled(self, on):
        self._on = on

    def get_volume(self):
        return self._volume

    def set_volume(self, level):
        self._volume = max(0, min(60, level))

class Remote:
    def __init__(self, device):
        self.device = device

    def toggle_power(self):
        self.device.set_enabled(not self.device.is_enabled())

    def volume_up(self):
        self.device.set_volume(self.device.get_volume() + 10)

class AdvancedRemote(Remote):
    def mute(self):
        self.device.set_volume(0)

tv, radio = TV(), Radio()
Remote(tv).toggle_power()
remote = AdvancedRemote(radio)
remote.toggle_power()
remote.volume_up()
remote.volume_up()
print(tv.is_enabled(), radio.is_enabled())  # Output: True True
print(radio.get_volume())                   # Output: 60
remote.device = tv
remote.mute()
print(tv.get_volume())                      # Output: 0

Two remotes and two devices take four concrete classes instead of four combined subclasses, and the gap widens with every addition: a projector is one new class that works with both remotes at once. The remote never knows how a device stores its volume or enforces its limit, which is why the radio stops at 60 without any change in volume_up. The last lines replace the device of an existing remote at run time, which inheritance cannot do, since a subclass is bound to its parent when the class is defined.

A Bridge in the Standard Library

The io module of Python applies the same separation to files. A text stream, io.TextIOWrapper, is the abstraction: it offers write and read with strings and handles encodings and newlines. The binary buffer beneath it is the implementation, and it may be a file on disk, a socket or a buffer in memory; the object returned by open in text mode is a TextIOWrapper over a BufferedWriter over a FileIO, verified in CPython 3.12. The following example places the same text abstraction over buffers in memory.

import io

raw = io.BytesIO()
text = io.TextIOWrapper(raw, encoding="utf-8", newline="")
text.write("café\n")
text.flush()
print(raw.getvalue())  # Output: b'caf\xc3\xa9\n'

raw = io.BytesIO()
text = io.TextIOWrapper(raw, encoding="utf-16-le", newline="")
text.write("ok")
text.flush()
print(raw.getvalue())  # Output: b'o\x00k\x00'

The text layer never asks where the bytes go, and the buffer never knows that they encode text, so new kinds of storage and new encodings are added independently. The call to flush is required because the text layer keeps its own buffer and passes data to the implementation only when it is flushed or closed.

Bridge, Adapter and Strategy

This section distinguishes the Bridge pattern from two patterns that share its structure, since all three hold a reference to another object and forward calls to it. The Adapter pattern converts the interface of a class that already exists into the interface that a client expects, so it is applied after the design, to reconcile code that was not written to work together; a bridge is planned in advance, so that two hierarchies can evolve separately from the start. The Strategy pattern, examined in the article devoted to the Strategy pattern, replaces one algorithm inside a single class, whereas a bridge separates two dimensions that both have several variants, so that the abstraction side has subclasses of its own as well.

Pitfalls of the Bridge Pattern

A bridge is only as independent as the interface between its two sides, so most of its errors come from that interface. Six pitfalls are distinguished, which are the following:

  1. An abstraction that bypasses the implementation. A refined abstraction that changes its own state instead of calling the primitives breaks the bridge, and the device never learns about the change.
  2. Primitives shaped like one abstraction. When the implementation interface copies the methods of one remote, every new remote requires new methods in every device, and the two hierarchies are coupled again.
  3. Silent default methods. A base class whose methods only contain pass lets an incomplete implementation fail without notice; an abstract base class, as described in the article devoted to abstract base classes, refuses to instantiate it.
  4. A bridge for a single dimension. With one implementation and no prospect of another, the extra layer of indirection adds classes without removing any.
  5. Confusing it with an adapter. Presenting a wrapper over an incompatible class as a bridge hides the fact that the two sides were not designed for each other.
  6. Shared implementation objects. Two abstractions that hold the same implementation object see each other's changes, which is sometimes the intent and sometimes a defect.

The first pitfall is reproduced in the following example.

class Radio:
    def __init__(self):
        self.volume = 50

    def set_volume(self, level):
        self.volume = level

class NaiveRemote:
    def __init__(self, device):
        self.device, self.muted = device, False

    def mute(self):
        self.muted = True

class BridgeRemote:
    def __init__(self, device):
        self.device = device

    def mute(self):
        self.device.set_volume(0)

first, second = Radio(), Radio()
NaiveRemote(first).mute()
BridgeRemote(second).mute()
print(first.volume, second.volume)  # Output: 50 0

The naive remote records that it is muted, but the radio keeps playing at volume 50; only the remote that expresses mute through the primitive set_volume reaches the device.

Choosing Between Inheritance and a Bridge

Consequently, the choice depends on how many dimensions vary and on whether the classes involved were designed together, as the following table summarizes.

Situation Recommended approach
One dimension of variation Plain inheritance or a single class
Two independent dimensions, each with several variants A bridge: an abstraction holding an implementation
One algorithm that changes inside one class The Strategy pattern, often a function
An existing class with an incompatible interface The Adapter pattern
The implementation must change at run time A bridge, replacing the implementation object

Conclusion

It is concluded that the Bridge pattern replaces a hierarchy of combined subclasses with two hierarchies joined by a reference, so that abstractions and implementations grow by addition rather than by multiplication, and that Python already applies it in the layers of the io module. This magic depends on an implementation interface made of primitives, on refined abstractions that use only those primitives and on keeping the pattern distinct from adapters and strategies. Offering a single, simple entry point to a subsystem made of many collaborating classes is the purpose of the Facade pattern, which is developed in a future article of this series.