Patterncore
Bridge pattern
Also called Bridge, Handle/Body, pimpl, pointer to implementation.
Split a class that varies in two ways into two class hierarchies, an abstraction and an implementation, and join them with a reference. Each hierarchy then grows without the other.
- Family
- structural-design
- Intent
- Separate an abstraction from its implementation, so that each can change and grow without the other.
- Also called
- Handle/Body
Intent
Separate an abstraction from its implementation, so that each can change and grow without the other.1 The abstraction is the interface that clients use. The implementation is a second interface with primitive operations. The abstraction holds a reference to an implementation object and calls it.
Problem
Design Patterns starts with a window abstraction for a user interface toolkit. The toolkit must run on more than one window system. A direct design is a subclass of the window for each window system. When the toolkit adds a kind of window, such as an icon window, it needs a subclass of that kind for each window system as well.1
The same shape appears in many programs. A drawing program has shapes, such as circles and squares, and output formats, such as plain text and SVG. With inheritance alone, each pair is a class:
Shape
|-- TextCircle |-- SvgCircle
|-- TextSquare |-- SvgSquare
Two shapes and two formats need four classes. Three shapes and three formats need nine. A fourth format adds three classes, one for each shape. The code that writes SVG is in two or three classes, and the code that computes the corners of a square is in each format's square. The count is the product of the two dimensions, and each class is bound to one format at compile time.
The forces are these. The program has two dimensions that change for different reasons and at different times. The client code wants to use a shape and not care how it is drawn. And the program may want to choose the format at run time, or share one format object between many shapes.
Solution
Split the one hierarchy into two, and join them with a reference. Design Patterns names four participants.1
- Abstraction defines the interface for clients. It holds a reference to an Implementor. Here it is
Shape. - RefinedAbstraction extends the Abstraction. Here it is
CircleandSquare. - Implementor defines the interface of the implementation classes. Its operations are usually primitive. The Abstraction builds its higher-level operations from them. Here it is
Renderer, withcircleandpolygon. - ConcreteImplementor implements the Implementor for one platform. Here it is
TextRendererandSvgRenderer.
Abstraction Implementor
Shape: renderer, draw(), scale() ------> Renderer: circle(), polygon()
^ ^ ^ ^
| | | |
Circle Square TextRenderer SvgRenderer
draw() calls draw() computes 4 corners
circle() and calls polygon()
Two shapes and two renderers are four classes. A third renderer adds one class. A third shape adds one class. The count is now a sum and not a product.
The two interfaces do not have to match. The Implementor offers what every platform can do. The Abstraction offers what clients want. Square.draw turns a square into four points and calls polygon. No renderer knows what a square is, and no shape knows what SVG is.
The abstraction must not know the concrete implementors
The bridge works only when the abstraction calls the Implementor interface and nothing else. A test of the concrete class in the abstraction joins the two hierarchies again. Each renderer added later then needs a change in each shape. When the change is forgotten, the result is wrong without an error:
This code runs but gives a wrong answer on purpose.
class TextRenderer:
pass
class SvgRenderer:
pass
class CanvasRenderer: # added later; Circle.draw was not changed
pass
class Circle:
def __init__(self, renderer, radius):
self.renderer = renderer
self.radius = radius
def draw(self):
# the abstraction picks its code by the class of the renderer
if isinstance(self.renderer, TextRenderer):
return f"circle radius {self.radius}"
if isinstance(self.renderer, SvgRenderer):
return f'<circle r="{self.radius}"/>'
return ""
for renderer in (TextRenderer(), SvgRenderer(), CanvasRenderer()):
print(f"{type(renderer).__name__}: {Circle(renderer, 2).draw()!r}")
TextRenderer: 'circle radius 2'
SvgRenderer: '<circle r="2"/>'
CanvasRenderer: ''
The canvas renderer draws nothing, and nothing reports it. The fix moves the format code into the renderers, behind a circle method that each renderer must define, as the examples do.
The degenerate case: one implementor and Pimpl
Design Patterns says that the pattern is useful even with one ConcreteImplementor.1 The split then has another purpose: a change in the implementation must not force a change in the client code. In C++, the private members of a class are part of its layout, so a change to them makes each client compile again. The C++ Core Guidelines describe the Pimpl idiom, a "pointer to implementation". The class in the header holds a std::unique_ptr to a class that only the source file defines. This isolates clients from changes in the implementation, at the cost of an indirection.2
#include <iostream>
#include <memory>
#include <string>
// widget.h: the part that clients include
class Widget {
public:
explicit Widget(std::string title);
~Widget(); // defined below, where Impl is a complete type
Widget(Widget&&) noexcept;
Widget& operator=(Widget&&) noexcept;
void rename(std::string title);
std::string describe() const;
private:
struct Impl; // declared here, defined in widget.cpp
std::unique_ptr<Impl> impl_;
};
// widget.cpp: a change here does not change widget.h
struct Widget::Impl {
std::string title;
int revisions = 0;
};
Widget::Widget(std::string title) : impl_(std::make_unique<Impl>()) { impl_->title = std::move(title); }
Widget::~Widget() = default;
Widget::Widget(Widget&&) noexcept = default;
Widget& Widget::operator=(Widget&&) noexcept = default;
void Widget::rename(std::string title) {
impl_->title = std::move(title);
++impl_->revisions;
}
std::string Widget::describe() const {
return impl_->title + " (revisions: " + std::to_string(impl_->revisions) + ")";
}
int main() {
Widget widget("draft");
widget.rename("report");
std::cout << widget.describe() << '\n';
}
report (revisions: 1)
The destructor and the move operations are declared in the class and defined after Impl. The std::unique_ptr must delete an Impl, and that needs the complete type. The Core Guidelines example has the same comment on its destructor.2 Design Patterns lists Handle/Body as another name for the pattern.1 The handle is the class that clients see, and the body is the implementation behind it.
Example
Each example file builds two shapes, a circle and a square, and two renderers, text and SVG. For each renderer, the program draws each shape, scales it by 2 and draws it again. Then it changes the renderer of one circle at run time.
| Language | Abstraction | Implementor |
|---|---|---|
| Python | abc.ABC subclasses with a renderer attribute |
abc.ABC subclasses |
| JavaScript | classes with a renderer field |
classes with the same method names |
| TypeScript | an abstract class |
an interface, implemented by object literals |
| Java | an abstract class with a protected field |
an interface |
| C# | an abstract class with a primary constructor |
an interface |
| Go | an interface and structs with a Renderer field |
an interface |
| Rust | a trait and structs with an Rc<dyn Renderer> field |
a trait |
| C++ | an abstract class with a std::shared_ptr<const Renderer> |
an abstract class |
from abc import ABC, abstractmethod
class Renderer(ABC):
"""The implementor: the primitive drawing operations of one output format."""
name: str
@abstractmethod
def circle(self, x: int, y: int, radius: int) -> str: ...
@abstractmethod
def polygon(self, points: list[tuple[int, int]]) -> str: ...
class TextRenderer(Renderer):
name = "text"
def circle(self, x, y, radius):
return f"circle at ({x}, {y}) radius {radius}"
def polygon(self, points):
return "polygon " + " ".join(f"({x}, {y})" for x, y in points)
class SvgRenderer(Renderer):
name = "svg"
def circle(self, x, y, radius):
return f'<circle cx="{x}" cy="{y}" r="{radius}"/>'
def polygon(self, points):
return '<polygon points="' + " ".join(f"{x},{y}" for x, y in points) + '"/>'
class Shape(ABC):
"""The abstraction: it holds a renderer and draws itself with the primitives."""
def __init__(self, renderer: Renderer):
self.renderer = renderer
@abstractmethod
def draw(self) -> str: ...
@abstractmethod
def scale(self, factor: int) -> None: ...
class Circle(Shape):
def __init__(self, renderer: Renderer, x: int, y: int, radius: int):
super().__init__(renderer)
self.x, self.y, self.radius = x, y, radius
def draw(self):
return self.renderer.circle(self.x, self.y, self.radius)
def scale(self, factor):
self.radius *= factor
class Square(Shape):
def __init__(self, renderer: Renderer, x: int, y: int, side: int):
super().__init__(renderer)
self.x, self.y, self.side = x, y, side
def draw(self):
x, y, s = self.x, self.y, self.side
return self.renderer.polygon([(x, y), (x + s, y), (x + s, y + s), (x, y + s)])
def scale(self, factor):
self.side *= factor
for renderer in (TextRenderer(), SvgRenderer()):
print(f"{renderer.name}:")
for shape in (Circle(renderer, 1, 1, 2), Square(renderer, 0, 0, 3)):
print(" ", shape.draw())
shape.scale(2)
print(" ", shape.draw())
circle = Circle(TextRenderer(), 1, 1, 2)
circle.renderer = SvgRenderer() # the implementation changes at run time
print("switched:", circle.draw())
text:
circle at (1, 1) radius 2
circle at (1, 1) radius 4
polygon (0, 0) (3, 0) (3, 3) (0, 3)
polygon (0, 0) (6, 0) (6, 6) (0, 6)
svg:
<circle cx="1" cy="1" r="2"/>
<circle cx="1" cy="1" r="4"/>
<polygon points="0,0 3,0 3,3 0,3"/>
<polygon points="0,0 6,0 6,6 0,6"/>
switched: <circle cx="1" cy="1" r="2"/>
- Verdict: idiom. Two class hierarchies,
ShapeandRenderer, and a reference from the first to the second.abc.ABCmarks the methods that each subclass must define. - Two shapes and two renderers need four classes. A third shape or a third renderer adds one class, not two or three.
- Duck typing makes the
Rendererbase class optional. Any object withcircleandpolygonmethods works. Atyping.Protocollets a type checker confirm this. Shapedoes not test which renderer it has. A test such asisinstance(renderer, SvgRenderer)in a shape couples the two hierarchies again. The node page shows that bug.
#include <iostream>
#include <memory>
#include <string>
#include <utility>
#include <vector>
struct Point {
int x, y;
};
// The implementor: the primitive drawing operations of one output format.
class Renderer {
public:
virtual ~Renderer() = default;
virtual std::string name() const = 0;
virtual std::string circle(int x, int y, int radius) const = 0;
virtual std::string polygon(const std::vector<Point>& points) const = 0;
};
class TextRenderer final : public Renderer {
public:
std::string name() const override { return "text"; }
std::string circle(int x, int y, int radius) const override {
return "circle at (" + std::to_string(x) + ", " + std::to_string(y) + ") radius " +
std::to_string(radius);
}
std::string polygon(const std::vector<Point>& points) const override {
std::string out = "polygon";
for (const auto& p : points) {
out += " (" + std::to_string(p.x) + ", " + std::to_string(p.y) + ")";
}
return out;
}
};
class SvgRenderer final : public Renderer {
public:
std::string name() const override { return "svg"; }
std::string circle(int x, int y, int radius) const override {
return "<circle cx=\"" + std::to_string(x) + "\" cy=\"" + std::to_string(y) + "\" r=\"" +
std::to_string(radius) + "\"/>";
}
std::string polygon(const std::vector<Point>& points) const override {
std::string out;
for (const auto& p : points) {
out += (out.empty() ? "" : " ") + std::to_string(p.x) + "," + std::to_string(p.y);
}
return "<polygon points=\"" + out + "\"/>";
}
};
// The abstraction: it holds a renderer and draws itself with the primitives.
class Shape {
public:
explicit Shape(std::shared_ptr<const Renderer> renderer) : renderer_(std::move(renderer)) {}
virtual ~Shape() = default;
void set_renderer(std::shared_ptr<const Renderer> renderer) { renderer_ = std::move(renderer); }
virtual std::string draw() const = 0;
virtual void scale(int factor) = 0;
protected:
std::shared_ptr<const Renderer> renderer_;
};
class Circle final : public Shape {
public:
Circle(std::shared_ptr<const Renderer> renderer, int x, int y, int radius)
: Shape(std::move(renderer)), x_(x), y_(y), radius_(radius) {}
std::string draw() const override { return renderer_->circle(x_, y_, radius_); }
void scale(int factor) override { radius_ *= factor; }
private:
int x_, y_, radius_;
};
class Square final : public Shape {
public:
Square(std::shared_ptr<const Renderer> renderer, int x, int y, int side)
: Shape(std::move(renderer)), x_(x), y_(y), side_(side) {}
std::string draw() const override {
return renderer_->polygon({{x_, y_}, {x_ + side_, y_}, {x_ + side_, y_ + side_}, {x_, y_ + side_}});
}
void scale(int factor) override { side_ *= factor; }
private:
int x_, y_, side_;
};
int main() {
std::vector<std::shared_ptr<const Renderer>> renderers{
std::make_shared<TextRenderer>(), std::make_shared<SvgRenderer>()};
for (const auto& renderer : renderers) {
std::cout << renderer->name() << ":\n";
std::vector<std::unique_ptr<Shape>> shapes;
shapes.push_back(std::make_unique<Circle>(renderer, 1, 1, 2));
shapes.push_back(std::make_unique<Square>(renderer, 0, 0, 3));
for (auto& shape : shapes) {
std::cout << " " << shape->draw() << '\n';
shape->scale(2);
std::cout << " " << shape->draw() << '\n';
}
}
Circle circle(std::make_shared<TextRenderer>(), 1, 1, 2);
circle.set_renderer(std::make_shared<SvgRenderer>()); // the implementation changes at run time
std::cout << "switched: " << circle.draw() << '\n';
}
text:
circle at (1, 1) radius 2
circle at (1, 1) radius 4
polygon (0, 0) (3, 0) (3, 3) (0, 3)
polygon (0, 0) (6, 0) (6, 6) (0, 6)
svg:
<circle cx="1" cy="1" r="2"/>
<circle cx="1" cy="1" r="4"/>
<polygon points="0,0 3,0 3,3 0,3"/>
<polygon points="0,0 6,0 6,6 0,6"/>
switched: <circle cx="1" cy="1" r="2"/>
- Verdict: idiom. Two abstract classes with pure virtual functions. The abstraction holds a
std::shared_ptr<const Renderer>, so many shapes can share one renderer. - The Pimpl idiom is the degenerate case with one implementor. A class holds a
std::unique_ptrto an incomplete type that its source file defines. The header then does not change when the implementation changes. The C++ Core Guidelines suggest it for a stable library ABI. The node page has an example. - A template parameter,
template <class R> class Circle, gives the static form: no virtual calls, but the renderer is fixed at compile time.
import java.util.List;
import java.util.stream.Collectors;
public class Main {
record Point(int x, int y) {}
// The implementor: the primitive drawing operations of one output format.
interface Renderer {
String name();
String circle(int x, int y, int radius);
String polygon(List<Point> points);
}
static final class TextRenderer implements Renderer {
public String name() { return "text"; }
public String circle(int x, int y, int radius) {
return "circle at (" + x + ", " + y + ") radius " + radius;
}
public String polygon(List<Point> points) {
return "polygon " + points.stream()
.map(p -> "(" + p.x() + ", " + p.y() + ")")
.collect(Collectors.joining(" "));
}
}
static final class SvgRenderer implements Renderer {
public String name() { return "svg"; }
public String circle(int x, int y, int radius) {
return "<circle cx=\"" + x + "\" cy=\"" + y + "\" r=\"" + radius + "\"/>";
}
public String polygon(List<Point> points) {
return "<polygon points=\"" + points.stream()
.map(p -> p.x() + "," + p.y())
.collect(Collectors.joining(" ")) + "\"/>";
}
}
// The abstraction: it holds a renderer and draws itself with the primitives.
abstract static class Shape {
protected Renderer renderer;
Shape(Renderer renderer) { this.renderer = renderer; }
void setRenderer(Renderer renderer) { this.renderer = renderer; }
abstract String draw();
abstract void scale(int factor);
}
static final class Circle extends Shape {
private final int x, y;
private int radius;
Circle(Renderer renderer, int x, int y, int radius) {
super(renderer);
this.x = x;
this.y = y;
this.radius = radius;
}
String draw() { return renderer.circle(x, y, radius); }
void scale(int factor) { radius *= factor; }
}
static final class Square extends Shape {
private final int x, y;
private int side;
Square(Renderer renderer, int x, int y, int side) {
super(renderer);
this.x = x;
this.y = y;
this.side = side;
}
String draw() {
return renderer.polygon(List.of(
new Point(x, y), new Point(x + side, y),
new Point(x + side, y + side), new Point(x, y + side)));
}
void scale(int factor) { side *= factor; }
}
public static void main(String[] args) {
for (Renderer renderer : List.of(new TextRenderer(), new SvgRenderer())) {
System.out.println(renderer.name() + ":");
for (Shape shape : List.of(new Circle(renderer, 1, 1, 2), new Square(renderer, 0, 0, 3))) {
System.out.println(" " + shape.draw());
shape.scale(2);
System.out.println(" " + shape.draw());
}
}
Shape circle = new Circle(new TextRenderer(), 1, 1, 2);
circle.setRenderer(new SvgRenderer()); // the implementation changes at run time
System.out.println("switched: " + circle.draw());
}
}
text:
circle at (1, 1) radius 2
circle at (1, 1) radius 4
polygon (0, 0) (3, 0) (3, 3) (0, 3)
polygon (0, 0) (6, 0) (6, 6) (0, 6)
svg:
<circle cx="1" cy="1" r="2"/>
<circle cx="1" cy="1" r="4"/>
<polygon points="0,0 3,0 3,3 0,3"/>
<polygon points="0,0 6,0 6,6 0,6"/>
switched: <circle cx="1" cy="1" r="2"/>
- Verdict: idiom. An
interfacefor the implementor, anabstract classfor the abstraction, and aprotectedfield that joins them. - The abstraction is a class hierarchy of its own, so it is an abstract class and not an interface: it holds state, the renderer, that all shapes share.
- JDBC has a related split.
java.sql.Driveris the interface that each database driver implements, and application code calls thejava.sqlinterfaces, not the driver classes.
using System;
using System.Collections.Generic;
using System.Linq;
foreach (IRenderer renderer in new IRenderer[] { new TextRenderer(), new SvgRenderer() })
{
Console.WriteLine($"{renderer.Name}:");
foreach (Shape shape in new Shape[] { new Circle(renderer, 1, 1, 2), new Square(renderer, 0, 0, 3) })
{
Console.WriteLine($" {shape.Draw()}");
shape.Scale(2);
Console.WriteLine($" {shape.Draw()}");
}
}
Shape circle = new Circle(new TextRenderer(), 1, 1, 2);
circle.Renderer = new SvgRenderer(); // the implementation changes at run time
Console.WriteLine($"switched: {circle.Draw()}");
// The implementor: the primitive drawing operations of one output format.
interface IRenderer
{
string Name { get; }
string Circle(int x, int y, int radius);
string Polygon(IEnumerable<(int X, int Y)> points);
}
sealed class TextRenderer : IRenderer
{
public string Name => "text";
public string Circle(int x, int y, int radius) => $"circle at ({x}, {y}) radius {radius}";
public string Polygon(IEnumerable<(int X, int Y)> points) =>
"polygon " + string.Join(" ", points.Select(p => $"({p.X}, {p.Y})"));
}
sealed class SvgRenderer : IRenderer
{
public string Name => "svg";
public string Circle(int x, int y, int radius) => $"<circle cx=\"{x}\" cy=\"{y}\" r=\"{radius}\"/>";
public string Polygon(IEnumerable<(int X, int Y)> points) =>
$"<polygon points=\"{string.Join(" ", points.Select(p => $"{p.X},{p.Y}"))}\"/>";
}
// The abstraction: it holds a renderer and draws itself with the primitives.
abstract class Shape(IRenderer renderer)
{
public IRenderer Renderer { get; set; } = renderer;
public abstract string Draw();
public abstract void Scale(int factor);
}
sealed class Circle(IRenderer renderer, int x, int y, int radius) : Shape(renderer)
{
private int radius = radius;
public override string Draw() => Renderer.Circle(x, y, radius);
public override void Scale(int factor) => radius *= factor;
}
sealed class Square(IRenderer renderer, int x, int y, int side) : Shape(renderer)
{
private int side = side;
public override string Draw() =>
Renderer.Polygon([(x, y), (x + side, y), (x + side, y + side), (x, y + side)]);
public override void Scale(int factor) => side *= factor;
}
text:
circle at (1, 1) radius 2
circle at (1, 1) radius 4
polygon (0, 0) (3, 0) (3, 3) (0, 3)
polygon (0, 0) (6, 0) (6, 6) (0, 6)
svg:
<circle cx="1" cy="1" r="2"/>
<circle cx="1" cy="1" r="4"/>
<polygon points="0,0 3,0 3,3 0,3"/>
<polygon points="0,0 6,0 6,6 0,6"/>
switched: <circle cx="1" cy="1" r="2"/>
- Verdict: idiom. An
interfacefor the implementor and anabstract classwith a primary constructor for the abstraction. - The
Rendererproperty has a setter, so a program can switch the implementation of one shape at run time. - A value tuple
(int X, int Y)stands in for a point type. The collection expression[(x, y), ...]builds the sequence forPolygon.
// The implementors: the primitive drawing operations of one output format.
class TextRenderer {
name = "text";
circle(x, y, radius) {
return `circle at (${x}, ${y}) radius ${radius}`;
}
polygon(points) {
return "polygon " + points.map(([x, y]) => `(${x}, ${y})`).join(" ");
}
}
class SvgRenderer {
name = "svg";
circle(x, y, radius) {
return `<circle cx="${x}" cy="${y}" r="${radius}"/>`;
}
polygon(points) {
return `<polygon points="${points.map(([x, y]) => `${x},${y}`).join(" ")}"/>`;
}
}
// The abstraction: it holds a renderer and draws itself with the primitives.
class Shape {
constructor(renderer) {
this.renderer = renderer;
}
}
class Circle extends Shape {
constructor(renderer, x, y, radius) {
super(renderer);
Object.assign(this, { x, y, radius });
}
draw() {
return this.renderer.circle(this.x, this.y, this.radius);
}
scale(factor) {
this.radius *= factor;
}
}
class Square extends Shape {
constructor(renderer, x, y, side) {
super(renderer);
Object.assign(this, { x, y, side });
}
draw() {
const { x, y, side: s } = this;
return this.renderer.polygon([[x, y], [x + s, y], [x + s, y + s], [x, y + s]]);
}
scale(factor) {
this.side *= factor;
}
}
for (const renderer of [new TextRenderer(), new SvgRenderer()]) {
console.log(`${renderer.name}:`);
for (const shape of [new Circle(renderer, 1, 1, 2), new Square(renderer, 0, 0, 3)]) {
console.log(" ", shape.draw());
shape.scale(2);
console.log(" ", shape.draw());
}
}
const circle = new Circle(new TextRenderer(), 1, 1, 2);
circle.renderer = new SvgRenderer(); // the implementation changes at run time
console.log("switched:", circle.draw());
text:
circle at (1, 1) radius 2
circle at (1, 1) radius 4
polygon (0, 0) (3, 0) (3, 3) (0, 3)
polygon (0, 0) (6, 0) (6, 6) (0, 6)
svg:
<circle cx="1" cy="1" r="2"/>
<circle cx="1" cy="1" r="4"/>
<polygon points="0,0 3,0 3,3 0,3"/>
<polygon points="0,0 6,0 6,6 0,6"/>
switched: <circle cx="1" cy="1" r="2"/>
- Verdict: idiom. A shape holds a renderer object and calls its methods. JavaScript has no interfaces, so the two renderer classes share only the names of their methods.
- A renderer can be a plain object literal with
circleandpolygonfunctions. A class is not required for the implementor side. - A mistake in a method name in one renderer shows up only when a shape calls it, as a
TypeErrorat run time. The TypeScript example checks the methods at compile time.
type Point = readonly [number, number];
// The implementor: the primitive drawing operations of one output format.
interface Renderer {
readonly name: string;
circle(x: number, y: number, radius: number): string;
polygon(points: readonly Point[]): string;
}
const textRenderer: Renderer = {
name: "text",
circle: (x, y, radius) => `circle at (${x}, ${y}) radius ${radius}`,
polygon: (points) => "polygon " + points.map(([x, y]) => `(${x}, ${y})`).join(" "),
};
const svgRenderer: Renderer = {
name: "svg",
circle: (x, y, radius) => `<circle cx="${x}" cy="${y}" r="${radius}"/>`,
polygon: (points) => `<polygon points="${points.map(([x, y]) => `${x},${y}`).join(" ")}"/>`,
};
// The abstraction: it holds a renderer and draws itself with the primitives.
abstract class Shape {
renderer: Renderer;
constructor(renderer: Renderer) {
this.renderer = renderer;
}
abstract draw(): string;
abstract scale(factor: number): void;
}
class Circle extends Shape {
private readonly x: number;
private readonly y: number;
private radius: number;
constructor(renderer: Renderer, x: number, y: number, radius: number) {
super(renderer);
this.x = x;
this.y = y;
this.radius = radius;
}
draw(): string {
return this.renderer.circle(this.x, this.y, this.radius);
}
scale(factor: number): void {
this.radius *= factor;
}
}
class Square extends Shape {
private readonly x: number;
private readonly y: number;
private side: number;
constructor(renderer: Renderer, x: number, y: number, side: number) {
super(renderer);
this.x = x;
this.y = y;
this.side = side;
}
draw(): string {
const { x, y, side: s } = this;
return this.renderer.polygon([[x, y], [x + s, y], [x + s, y + s], [x, y + s]]);
}
scale(factor: number): void {
this.side *= factor;
}
}
for (const renderer of [textRenderer, svgRenderer]) {
console.log(`${renderer.name}:`);
for (const shape of [new Circle(renderer, 1, 1, 2), new Square(renderer, 0, 0, 3)]) {
console.log(" ", shape.draw());
shape.scale(2);
console.log(" ", shape.draw());
}
}
const circle = new Circle(textRenderer, 1, 1, 2);
circle.renderer = svgRenderer; // the implementation changes at run time
console.log("switched:", circle.draw());
text:
circle at (1, 1) radius 2
circle at (1, 1) radius 4
polygon (0, 0) (3, 0) (3, 3) (0, 3)
polygon (0, 0) (6, 0) (6, 6) (0, 6)
svg:
<circle cx="1" cy="1" r="2"/>
<circle cx="1" cy="1" r="4"/>
<polygon points="0,0 3,0 3,3 0,3"/>
<polygon points="0,0 6,0 6,6 0,6"/>
switched: <circle cx="1" cy="1" r="2"/>
- Verdict: idiom. An
interfacefor the implementor and anabstract classfor the abstraction. The compiler checks that each renderer has both methods with the right parameter types. - The renderers are object literals, not classes. A structural type system accepts any object with the right shape, so the implementor side needs no class hierarchy.
- The fields are declared and assigned one by one. Constructor parameter properties such as
private x: numberwould be shorter, but they are TypeScript syntax that emits code, and Node.js type stripping rejects them withERR_UNSUPPORTED_TYPESCRIPT_SYNTAX.
package main
import (
"fmt"
"strings"
)
type Point struct{ X, Y int }
// Renderer is the implementor: the primitive drawing operations of one output format.
type Renderer interface {
Name() string
Circle(x, y, radius int) string
Polygon(points []Point) string
}
type TextRenderer struct{}
func (TextRenderer) Name() string { return "text" }
func (TextRenderer) Circle(x, y, radius int) string {
return fmt.Sprintf("circle at (%d, %d) radius %d", x, y, radius)
}
func (TextRenderer) Polygon(points []Point) string {
parts := make([]string, len(points))
for i, p := range points {
parts[i] = fmt.Sprintf("(%d, %d)", p.X, p.Y)
}
return "polygon " + strings.Join(parts, " ")
}
type SvgRenderer struct{}
func (SvgRenderer) Name() string { return "svg" }
func (SvgRenderer) Circle(x, y, radius int) string {
return fmt.Sprintf(`<circle cx="%d" cy="%d" r="%d"/>`, x, y, radius)
}
func (SvgRenderer) Polygon(points []Point) string {
parts := make([]string, len(points))
for i, p := range points {
parts[i] = fmt.Sprintf("%d,%d", p.X, p.Y)
}
return `<polygon points="` + strings.Join(parts, " ") + `"/>`
}
// Shape is the abstraction. Each shape holds a Renderer in a field.
type Shape interface {
Draw() string
Scale(factor int)
}
type Circle struct {
Renderer Renderer
X, Y, Radius int
}
func (c *Circle) Draw() string { return c.Renderer.Circle(c.X, c.Y, c.Radius) }
func (c *Circle) Scale(factor int) { c.Radius *= factor }
type Square struct {
Renderer Renderer
X, Y, Side int
}
func (s *Square) Draw() string {
x, y, d := s.X, s.Y, s.Side
return s.Renderer.Polygon([]Point{{x, y}, {x + d, y}, {x + d, y + d}, {x, y + d}})
}
func (s *Square) Scale(factor int) { s.Side *= factor }
func main() {
for _, renderer := range []Renderer{TextRenderer{}, SvgRenderer{}} {
fmt.Printf("%s:\n", renderer.Name())
for _, shape := range []Shape{&Circle{renderer, 1, 1, 2}, &Square{renderer, 0, 0, 3}} {
fmt.Println(" ", shape.Draw())
shape.Scale(2)
fmt.Println(" ", shape.Draw())
}
}
circle := &Circle{TextRenderer{}, 1, 1, 2}
circle.Renderer = SvgRenderer{} // the implementation changes at run time
fmt.Println("switched:", circle.Draw())
}
text:
circle at (1, 1) radius 2
circle at (1, 1) radius 4
polygon (0, 0) (3, 0) (3, 3) (0, 3)
polygon (0, 0) (6, 0) (6, 6) (0, 6)
svg:
<circle cx="1" cy="1" r="2"/>
<circle cx="1" cy="1" r="4"/>
<polygon points="0,0 3,0 3,3 0,3"/>
<polygon points="0,0 6,0 6,6 0,6"/>
switched: <circle cx="1" cy="1" r="2"/>
- Verdict: idiom. Two interfaces and a struct field of the implementor's interface type. Go has no inheritance, so each shape declares its own
Rendererfield. - An embedded struct can hold the shared field for all shapes, but each shape still writes its own
Draw. The abstraction side has no base class with shared code. log/sloghas this structure. ALoggeris associated with aHandler, and aLoggeroutput method creates aRecordand passes it to theHandler.database/sqlis a second case:sql.DBworks with any package that implements the interfaces indatabase/sql/driver.
use std::rc::Rc;
/// The implementor: the primitive drawing operations of one output format.
trait Renderer {
fn name(&self) -> &str;
fn circle(&self, x: i32, y: i32, radius: i32) -> String;
fn polygon(&self, points: &[(i32, i32)]) -> String;
}
struct TextRenderer;
impl Renderer for TextRenderer {
fn name(&self) -> &str {
"text"
}
fn circle(&self, x: i32, y: i32, radius: i32) -> String {
format!("circle at ({x}, {y}) radius {radius}")
}
fn polygon(&self, points: &[(i32, i32)]) -> String {
let parts: Vec<String> = points.iter().map(|(x, y)| format!("({x}, {y})")).collect();
format!("polygon {}", parts.join(" "))
}
}
struct SvgRenderer;
impl Renderer for SvgRenderer {
fn name(&self) -> &str {
"svg"
}
fn circle(&self, x: i32, y: i32, radius: i32) -> String {
format!(r#"<circle cx="{x}" cy="{y}" r="{radius}"/>"#)
}
fn polygon(&self, points: &[(i32, i32)]) -> String {
let parts: Vec<String> = points.iter().map(|(x, y)| format!("{x},{y}")).collect();
format!(r#"<polygon points="{}"/>"#, parts.join(" "))
}
}
/// The abstraction. Each shape holds a shared pointer to a renderer.
trait Shape {
fn draw(&self) -> String;
fn scale(&mut self, factor: i32);
}
struct Circle {
renderer: Rc<dyn Renderer>,
x: i32,
y: i32,
radius: i32,
}
impl Shape for Circle {
fn draw(&self) -> String {
self.renderer.circle(self.x, self.y, self.radius)
}
fn scale(&mut self, factor: i32) {
self.radius *= factor;
}
}
struct Square {
renderer: Rc<dyn Renderer>,
x: i32,
y: i32,
side: i32,
}
impl Shape for Square {
fn draw(&self) -> String {
let (x, y, s) = (self.x, self.y, self.side);
self.renderer.polygon(&[(x, y), (x + s, y), (x + s, y + s), (x, y + s)])
}
fn scale(&mut self, factor: i32) {
self.side *= factor;
}
}
fn main() {
let renderers: Vec<Rc<dyn Renderer>> = vec![Rc::new(TextRenderer), Rc::new(SvgRenderer)];
for renderer in &renderers {
println!("{}:", renderer.name());
let mut shapes: Vec<Box<dyn Shape>> = vec![
Box::new(Circle { renderer: Rc::clone(renderer), x: 1, y: 1, radius: 2 }),
Box::new(Square { renderer: Rc::clone(renderer), x: 0, y: 0, side: 3 }),
];
for shape in shapes.iter_mut() {
println!(" {}", shape.draw());
shape.scale(2);
println!(" {}", shape.draw());
}
}
let mut circle = Circle { renderer: Rc::new(TextRenderer), x: 1, y: 1, radius: 2 };
circle.renderer = Rc::new(SvgRenderer); // the implementation changes at run time
println!("switched: {}", circle.draw());
}
text:
circle at (1, 1) radius 2
circle at (1, 1) radius 4
polygon (0, 0) (3, 0) (3, 3) (0, 3)
polygon (0, 0) (6, 0) (6, 6) (0, 6)
svg:
<circle cx="1" cy="1" r="2"/>
<circle cx="1" cy="1" r="4"/>
<polygon points="0,0 3,0 3,3 0,3"/>
<polygon points="0,0 6,0 6,6 0,6"/>
switched: <circle cx="1" cy="1" r="2"/>
- Verdict: idiom. Two traits and a field of type
Rc<dyn Renderer>. Many shapes share one renderer through the reference count. - A generic field,
struct Circle<R: Renderer> { renderer: R }, is the static form. The compiler then makes a separateCirclefor each renderer type, and a call needs no dynamic dispatch. The price is that the renderer of a shape cannot change at run time, and shapes with different renderers cannot go in oneVecwithout a trait object. - The renderers have no fields, so they are zero-sized types.
Rc::new(TextRenderer)still allocates the reference counts.
Consequences
Design Patterns lists three consequences.1
- The interface and the implementation are decoupled. The implementation is not bound to the abstraction for good. A program can choose it, or change it, at run time. A change to an implementation class does not force a change to the abstraction and its clients.
- Extensibility improves. The Abstraction and Implementor hierarchies grow on their own.
- Clients do not see the implementation details. Design Patterns gives the sharing of implementor objects as an example.
The costs are these. Each call from the abstraction to the implementor is an indirect call through a reference. The design has two hierarchies and an extra interface, so a reader must follow the reference to see what a call does. And the Implementor interface is hard to change. Each primitive operation must work for each implementor, and a primitive that one platform cannot do well is a problem for all of them. The split is a guess about which way the code will vary. When the guess is wrong, the cost of the extra interface buys nothing.
When not to use it
Do not use it when there is one dimension of change. A class with several implementations is an interface with several classes, or a Strategy pattern. Bridge is for the case where the abstraction itself also has subclasses.
Do not use it when one of the two dimensions has one member and will not grow, unless the purpose is the compile-time isolation of Pimpl. One renderer behind a Renderer interface is one more file and one more indirection.
Do not use it to join two interfaces that already exist. That is Adapter pattern.
Do not build it for the platform choice when the language or the build does that already. Go includes a file in a package only when its build constraints hold, and a name such as source_windows.go is a constraint on the target system.6 C and C++ select code with the preprocessor. These choose an implementation at build time with no interface and no reference. A run-time bridge is needed when the choice is made at run time, or when one program uses more than one implementation.
Variants and related patterns
Adapter. Both patterns forward calls from one interface to another object. Design Patterns draws the difference by time. An adapter makes two classes work together after they are designed. A bridge is designed up front, so that the abstraction and the implementation can vary on their own.1 An adapter changes an interface that exists. A bridge defines both interfaces for this purpose. See Adapter pattern.
Strategy. The class diagrams of Bridge and Strategy look the same: an object holds a reference to an interface, and calls it. The difference is in the purpose and in the two sides. A strategy is an algorithm that a client chooses for a context. The context is usually one class, and the strategy interface is often one method. A bridge splits a class hierarchy in two. The abstraction has its own subclasses, and the implementor interface is a set of primitive operations from which the abstraction builds its own operations. Strategy is a behavioural pattern about a choice of algorithm. Bridge is a structural pattern about the shape of two hierarchies. See Strategy pattern.
Abstract Factory. Design Patterns says that an abstract factory can create and configure a particular bridge.1 When a program must pick a set of implementors that work together, such as the windows, fonts and colours of one window system, a factory for that platform makes them. See Abstract Factory pattern.
State. A state object is also an implementation behind a reference. The context replaces it when its state changes, and the client does not choose it. See State pattern.
Proxy and Decorator. These also hold a reference to another object, but they have the same interface as that object. A bridge's abstraction and implementor have different interfaces. See Proxy pattern and Decorator pattern.
Static bridge. A generic or template parameter can take the place of the reference: Circle<R: Renderer> in Rust, template <class R> class Circle in C++. The compiler makes one class for each implementor, and calls need no dynamic dispatch. The price is that the implementor is fixed at compile time and is part of the type.
Known uses
- Go
log/slog: eachLoggeris associated with aHandler. ALoggeroutput method creates aRecordfrom its arguments and passes it to theHandler, which decides how to handle it.3 TheLoggerhas the convenience methods, and eachHandlerimplements a small interface. - Go
database/sql: the package must be used together with a database driver.4 Packagedatabase/sql/driverdefines the interfaces that the drivers implement.5sql.DB, which manages a pool of connections, is the abstraction, and each driver is an implementor. - C++ libraries that keep a stable ABI use the Pimpl idiom, which the C++ Core Guidelines recommend for this purpose.2
References
- Gamma, Helm, Johnson and Vlissides, Design Patterns, Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994, Chapter 4, Bridge (Intent, Also Known As, Motivation, Applicability, Participants, Consequences, Implementation, Related Patterns)
- C++ Core Guidelines, I.27, For stable library ABI, consider the Pimpl idiom (Reason, Example)
- Go standard library, package slog, package overview; type Handler; Writing a handler
- Go standard library, package sql, package overview; type DB
- Go standard library, package driver, package overview
- Go standard library, package build, Build Constraints
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag GA90WF Edit this page History Report an error Markdown