រចនាសម្ព័ន្ធ កម្រិតស្មុគស្មាញ: មធ្យម

Bridge in Go

Separate an abstraction from its implementation so both sides can vary independently without multiplying concrete types.

The Problem

When two dimensions of variation grow independently, inheritance-style combinations explode. A notification system might support several alert types and several delivery channels. Hardcoding every combination leads to duplicate logic and tight coupling between the abstraction and the concrete implementation.

The Solution

Bridge splits the high-level abstraction from the low-level implementor. In Go, one struct owns the business intent, while another interface handles the platform-specific work. Each side can change independently, and new combinations come from composition instead of subclass multiplication.

Structure

  • Implementor interface: MessageSender hides how messages are delivered.
  • Concrete implementors: Slack and email senders provide channel-specific behavior.
  • Abstractions: Different alert types format different business messages.
  • Client: Chooses an alert type and a sender, then composes them together.

Implementation

This example models two alert abstractions on top of two delivery mechanisms. Inventory alerts and incident alerts can both flow through email or Slack without creating a new concrete type for every pair.

package main

type MessageSender interface {
	Send(message string)
}

type Alert interface {
	Notify()
}

Best Practices

  • Use Bridge when two axes change independently and combinations would otherwise multiply.
  • Keep the abstraction focused on business meaning and the implementor focused on delivery details.
  • Inject the implementor so tests can verify the abstraction without real infrastructure.
  • Avoid overly generic implementor interfaces. The bridge still needs a domain-shaped contract.
  • Do not confuse Bridge with Adapter. Bridge designs for independent variation up front; Adapter translates after the fact.

When to Use

  • You have two orthogonal dimensions of variation such as alert type and delivery channel.
  • You want to add new business abstractions without touching channel code, or vice versa.
  • Composition can model the problem more cleanly than multiplying concrete structs.

When NOT to Use

  • Only one dimension actually varies.
  • A single interface plus a few concrete implementations already keeps the code clear.
  • The bridge adds indirection without eliminating any real duplication.