# Bridge: Separating Abstraction from Implementation

In software development, applications often need to support multiple variations of the same functionality. The challenge is not necessarily implementing each variation, but designing the application so that these variations can evolve without becoming tightly coupled.

Imagine that you are extending our ticket-management application to generate reports. The application needs to produce open tickets reports and SLA breaches reports. Both reports must be available in CSV and HTML formats.

One straightforward approach would be to create a separate class for every combination:

- `OpenTicketsCsvReport`
- `OpenTicketsHtmlReport`
- `SlaBreachesCsvReport`
- `SlaBreachesHtmlReport`

Initially, this seems reasonable. We have two report types and two output formats, resulting in four classes.

However, what happens when the application needs a customer activity report and PDF as another output format?

We now have three report types and three output formats, potentially requiring nine classes.

The problem is that we are trying to manage two independent dimensions of variation within a single inheritance hierarchy:

- What information should the report contain?
- How should that information be presented?

As the application grows, combining these responsibilities through inheritance creates more classes and makes the design increasingly difficult to maintain.

We need a way to separate these dimensions so that report types and rendering formats can evolve independently.

This is where the Bridge pattern becomes useful.

## What is the Bridge pattern?

The Bridge pattern is a structural design pattern that decouples an abstraction from its implementation so that both can vary independently.

It separates a high-level responsibility from the lower-level mechanism used to carry it out.

Instead of putting everything into one inheritance hierarchy, Bridge introduces two separate hierarchies:

- **Abstraction:** Defines the high-level operations and business logic.
- **Implementation:** Defines the lower-level operations used by the abstraction to perform its work.

The abstraction maintains a reference to an implementation and delegates the relevant work to it.

In our ticket-management example, `TicketReport` represents the high-level reporting responsibility, while `ITicketReportRenderer` represents the mechanism used to render the report.

The report does not need to know whether its output will be CSV or HTML. It only needs to work with the renderer's contract.

An important clarification: the terms *abstraction* and *implementation* describe architectural roles. They do not simply mean a C# abstract class and a class implementing an interface. Our example uses an abstract class for the abstraction, but the Bridge pattern does not require that language construct.

## Understanding the participants

The Bridge pattern has five main participants:

| Participant | Responsibility | Ticket-management example |
| --- | --- | --- |
| Abstraction | Defines the high-level operations and maintains a reference to an implementation. | `TicketReport` |
| Refined Abstraction | Extends the abstraction with specific high-level behaviour. | `OpenTicketsReport`, `SlaBreachesReport` |
| Implementor | Defines the interface for the implementation operations. | `ITicketReportRenderer` |
| Concrete Implementor | Provides a specific implementation of the implementor interface. | `CsvTicketReportRenderer`, `HtmlTicketReportRenderer` |
| Client | Connects the abstraction with an appropriate implementation. | Report creation or export service |

The relationship is straightforward:

1. The abstraction maintains a reference to the implementor interface.
2. Refined abstractions extend the high-level behaviour.
3. Concrete implementors provide different ways of carrying out the lower-level operations.
4. The client connects a particular abstraction with an implementation.

The important point is that the two hierarchies can grow independently.

We can introduce a new report type without modifying the existing renderers. Similarly, we can introduce a new renderer without changing the existing report classes, provided the shared contract remains suitable.

## Implementing Bridge in C#

Let's return to our ticket-management application and implement the reporting solution.

### 1\. Define the report data and implementation interface

First, we need a consistent data structure that both report types and renderers can understand.

```csharp
public enum TicketStatus
{
    Open,
    InProgress,
    Resolved
}

public sealed record TicketSummary(
    string Reference,
    string Title,
    TicketStatus Status,
    bool HasBreachedSla);

public sealed record TicketReportRow(
    string Reference,
    string Title,
    string Status);

public sealed record TicketReportData(
    string Title,
    IReadOnlyList<TicketReportRow> Rows);
```

Next, define the implementor interface:

```csharp
public interface ITicketReportRenderer
{
    string Render(TicketReportData report);
}
```

This interface defines the operations available to the abstraction. It does not need to mirror the methods exposed by `TicketReport`.

Its responsibility is deliberately narrow: accept report data and produce a representation.

### 2\. Create the abstraction

The `TicketReport` class represents the high-level reporting workflow.

It maintains a reference to `ITicketReportRenderer`, builds the report data and delegates the rendering operation.

```csharp
public abstract class TicketReport
{
    private readonly ITicketReportRenderer _renderer;

    protected TicketReport(ITicketReportRenderer renderer)
    {
        _renderer = renderer
            ?? throw new ArgumentNullException(nameof(renderer));
    }

    public string Export()
    {
        TicketReportData report = BuildReportData();

        return _renderer.Render(report);
    }

    protected abstract TicketReportData BuildReportData();
}
```

Notice that `TicketReport` does not contain CSV formatting or HTML generation logic.

It concentrates on the high-level reporting workflow and delegates the output operation to its linked renderer.

This separation is the central idea behind Bridge.

### 3\. Implement the refined abstractions

Our first refined abstraction is `OpenTicketsReport`.

It determines which tickets belong in the report and converts them into the shared report data structure.

```csharp
public sealed class OpenTicketsReport : TicketReport
{
    private readonly IReadOnlyCollection<TicketSummary> _tickets;

    public OpenTicketsReport(
        ITicketReportRenderer renderer,
        IReadOnlyCollection<TicketSummary> tickets)
        : base(renderer)
    {
        _tickets = tickets
            ?? throw new ArgumentNullException(nameof(tickets));
    }

    protected override TicketReportData BuildReportData()
    {
        var rows = _tickets
            .Where(ticket => ticket.Status != TicketStatus.Resolved)
            .Select(ticket => new TicketReportRow(
                ticket.Reference,
                ticket.Title,
                ticket.Status.ToString()))
            .ToArray();

        return new TicketReportData("Open tickets", rows);
    }
}
```

We can introduce another refined abstraction for SLA breaches:

```csharp
public sealed class SlaBreachesReport : TicketReport
{
    private readonly IReadOnlyCollection<TicketSummary> _tickets;

    public SlaBreachesReport(
        ITicketReportRenderer renderer,
        IReadOnlyCollection<TicketSummary> tickets)
        : base(renderer)
    {
        _tickets = tickets
            ?? throw new ArgumentNullException(nameof(tickets));
    }

    protected override TicketReportData BuildReportData()
    {
        var rows = _tickets
            .Where(ticket => ticket.HasBreachedSla)
            .Select(ticket => new TicketReportRow(
                ticket.Reference,
                ticket.Title,
                ticket.Status.ToString()))
            .ToArray();

        return new TicketReportData("SLA breaches", rows);
    }
}
```

Each report class is responsible for deciding what information belongs in its report. Neither class needs to know how that information will be rendered.

### 4\. Create the concrete implementors

Now we can provide different rendering mechanisms.

The first implementation generates CSV output:

```csharp
public sealed class CsvTicketReportRenderer
    : ITicketReportRenderer
{
    public string Render(TicketReportData report)
    {
        var rows = report.Rows.Select(row =>
            string.Join(",", new[]
            {
                Escape(row.Reference),
                Escape(row.Title),
                Escape(row.Status)
            }));

        return string.Join(
            Environment.NewLine,
            new[] { "Reference,Title,Status" }.Concat(rows));
    }

    private static string Escape(string value)
    {
        string escaped = value.Replace("\"", "\"\"");
        return $"\"{escaped}\"";
    }
}
```

The second implementation generates HTML:

```csharp
using System.Text.Encodings.Web;

public sealed class HtmlTicketReportRenderer
    : ITicketReportRenderer
{
    public string Render(TicketReportData report)
    {
        var rows = string.Join(
            Environment.NewLine,
            report.Rows.Select(row =>
                $"<tr><td>{EncodeHtml(row.Reference)}</td>" +
                $"<td>{EncodeHtml(row.Title)}</td>" +
                $"<td>{EncodeHtml(row.Status)}</td></tr>"));

        return $"<h1>{EncodeHtml(report.Title)}</h1>" +
               "<table><thead><tr>" +
               "<th>Reference</th><th>Title</th><th>Status</th>" +
               "</tr></thead>" +
               $"<tbody>{rows}</tbody></table>";
    }

    private static string EncodeHtml(string value) =>
        HtmlEncoder.Default.Encode(value);
}
```

Both implementations follow the same interface, but their internal behaviour is different.

The CSV renderer handles CSV formatting and escaping. The HTML renderer produces HTML and encodes values before inserting them into markup.

Neither needs to know whether the supplied data came from an open tickets report or an SLA breaches report.

### 5\. Connect the two hierarchies

The client decides which report and renderer to combine.

For example:

```csharp
TicketReport report = new OpenTicketsReport(
    new CsvTicketReportRenderer(),
    tickets);

string csvOutput = report.Export();
```

To generate the same report as HTML, we only change the renderer:

```csharp
TicketReport report = new OpenTicketsReport(
    new HtmlTicketReportRenderer(),
    tickets);

string htmlOutput = report.Export();
```

The report logic remains untouched.

Likewise, we can generate an SLA breaches report using either renderer:

| Report type | CSV renderer | HTML renderer |
| --- | --- | --- |
| Open tickets | `OpenTicketsReport` + `CsvTicketReportRenderer` | `OpenTicketsReport` + `HtmlTicketReportRenderer` |
| SLA breaches | `SlaBreachesReport` + `CsvTicketReportRenderer` | `SlaBreachesReport` + `HtmlTicketReportRenderer` |

We have four possible combinations without creating four separate report classes.

Adding a third report type or a third output format does not require modifying the existing hierarchy. We simply extend the appropriate side.

In a real application, report data would normally come from application services or repository queries. The example keeps that detail separate so we can focus on the Bridge structure.

## When should you use the Bridge pattern?

The Bridge pattern is particularly useful when:

1. **You have two independent dimensions of variation.**

   For example, different report types and different output formats. Each dimension should be able to evolve without requiring changes to the other.
2. **You expect both hierarchies to grow.**

   If new report types and rendering formats are likely to be introduced, separating them can prevent an increasingly complicated inheritance structure.
3. **You want to isolate platform or infrastructure details.**

   A high-level component should not need to understand the details of a specific underlying implementation.
4. **You need to switch implementations.**

   An abstraction can work with different implementations without changing its high-level behaviour.

Common examples include separating GUI controls from operating-system-specific APIs, business operations from infrastructure mechanisms, and document types from rendering engines.

However, Bridge should not be introduced into every class that has a dependency.

If a class is cohesive, has one stable responsibility and is unlikely to vary along multiple dimensions, adding two hierarchies and another interface may create more complexity than value.

## Advantages and trade-offs

Like every design pattern, Bridge introduces benefits as well as costs.

**Advantages**

- **Independent evolution:** Abstraction and implementation can be extended separately.
- **Reduced inheritance complexity:** Avoids creating a subclass for every combination of variations.
- **Separation of concerns:** High-level business logic remains separate from lower-level implementation details.
- **Runtime flexibility:** The abstraction can work with different implementations, depending on how the client connects them.

**Disadvantages**

- **Additional complexity:** More interfaces, classes and relationships need to be understood and maintained.
- **Extra indirection:** Work is delegated through another object, which can make the flow harder to trace.
- **Design effort:** The two dimensions and their shared contract must be identified correctly. Poorly chosen abstractions can make the design harder to extend rather than easier.

Bridge is most valuable when the independence of the two dimensions justifies the added structure.

## Bridge in modern .NET applications

The Bridge pattern fits naturally into applications built with [ASP.NET](http://ASP.NET) Core and dependency injection.

Instead of manually constructing the renderer wherever it is required, we can register the implementations with the dependency injection container.

For applications supporting multiple rendering formats, .NET 8 and later also support keyed dependency injection:

```csharp
builder.Services.AddKeyedTransient<
    ITicketReportRenderer,
    CsvTicketReportRenderer>("csv");

builder.Services.AddKeyedTransient<
    ITicketReportRenderer,
    HtmlTicketReportRenderer>("html");
```

The application can resolve a renderer using the relevant key when constructing the report.

For example, a report creation service could select the appropriate renderer based on the requested export format.

However, dependency injection is not itself the Bridge pattern.

- Bridge is the design decision to separate two independently evolving responsibilities.
- Dependency Injection manages object construction and supplies dependencies.
- Keyed services provide a convenient way to register and resolve multiple implementations of the same interface.

Simply injecting an interface does not automatically mean a design is using Bridge. The important part is the separation between the abstraction and its implementation.

## Bridge vs. Adapter and Strategy

Bridge is often confused with Adapter and Strategy because all three can use composition and delegation.

However, their intentions are different.

| Pattern | Primary intention | Typical question |
| --- | --- | --- |
| Adapter | Makes an existing incompatible interface usable by a client. | How can these two components work together? |
| Bridge | Separates two independent dimensions so they can evolve separately. | How can these two hierarchies vary independently? |
| Strategy | Encapsulates interchangeable algorithms or behaviours. | Which algorithm should perform this operation? |

The most important distinction is between Bridge and Adapter.

Adapter is commonly introduced after components already exist and their interfaces do not match. Bridge is generally designed into the application to prevent two dimensions of variation from becoming tightly coupled.

Bridge and Strategy can have similar structures, but Strategy focuses on selecting an algorithm or behaviour. Bridge focuses on separating an abstraction from its implementation so both hierarchies can evolve independently.

The structure alone does not identify a design pattern. The problem being solved does.

## Conclusion

The Bridge pattern provides a way to separate two independent dimensions of an application so that they can evolve without becoming tightly coupled.

In our ticket-management example, report generation and report rendering are separate responsibilities. By introducing an abstraction and an implementation hierarchy, we can add new report types and output formats without creating a growing collection of combination classes.

The broader lesson is that inheritance is not always the best way to extend a design. When independent responsibilities are forced into one hierarchy, composition can provide a more flexible structure.

However, Bridge is not always necessary. If there is no genuine need for the two dimensions to vary independently, the additional abstractions may introduce more complexity than they remove.

The value of the pattern comes from separating responsibilities that genuinely need to evolve independently.

Next, we'll explore the Composite pattern, which allows us to organise individual objects and groups of objects into tree structures while treating them consistently.

## Further reading

1. Alexander Shvets — *Dive Into Design Patterns*. Structural Design Patterns — Bridge, pp. 164–178.
2. Vaskaran Sarcar — *Design Patterns in C#*, 2nd Edition. Chapter 12 — Bridge Pattern, pp. 211–232.
3. [Microsoft Learn — Dependency injection in ASP.NET Core](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection).
4. [Microsoft Learn — Keyed services in .NET](https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection#keyed-services).
