Patterns: composition · 3 MIN READ
Bridge: two independent dimensions of variation
Compose an abstraction with a separately variable implementation.
Compose an abstraction with a separately variable implementation. Bridge separates an abstraction from its implementation so each can vary independently. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.
Structural pattern · A MAP OF THE IDEA
- Abstraction chooses content
- Bridge delegates rendering
- Implementation chooses output form
Useful when
- Two variation axes would multiply concrete types
- Implementations should be reused by several abstractions
Watch out
- One variation axis may need only a function
- More contracts increase navigation cost
Implementation & operation cost: Medium
Fit depends on the task
Editorial suitability, not benchmarks or a universal ranking. Styles describe different axes and can be combined.
The design decision
Bridge separates an abstraction from its implementation so each can vary independently. A report can choose its content shape while a renderer chooses output format. This is useful when otherwise every shape-format combination would become a distinct type.
A complete Go example
Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.
package main
import (
"fmt"
"strings"
)
type Renderer func(string) string
type Report struct {
Title string
Render Renderer
}
func (r Report) Output() string { return r.Render(r.Title) }
func Plain(s string) string { return s }
func Loud(s string) string { return strings.ToUpper(s) }
func main() {
fmt.Println(Report{Title: "daily", Render: Plain}.Output())
fmt.Println(Report{Title: "weekly", Render: Loud}.Output())
}
// Output:
// daily
// WEEKLY
Report data and rendering policy vary separately through composition. A different report abstraction can reuse the same renderer. The function contract stays small because only one operation varies in this example.
Tradeoffs and the simpler alternative
If only one dimension varies, Strategy or a direct function argument may describe the design more clearly. Bridge is planned separation; Adapter often retrofits existing incompatible APIs. Do not add both layers when there is no second independent variation.
TAKE THIS WITH YOU
Separates two independently varying design dimensions. If only one dimension varies, Strategy or a direct function argument may describe the design more clearly. Bridge is planned separation; Adapter often retrofits existing incompatible APIs. Do not add both layers when there is no second independent variation.
Check your understanding
Which statement best describes Bridge: two independent dimensions of variation?
Go to the source
Progress stays in this browser. No account needed.