00:00

Bridge Design Pattern in Java

Last updated:

The bridge design pattern in Java splits a class that varies in two independent directions into two separate hierarchies, an abstraction and an implementation, and connects them with a reference instead of inheritance. Each side can then grow on its own, so adding a new payment type or a new payment rail means writing one class, not one class per combination.

It matters because inheritance multiplies. Two payment types on two rails need four subclasses; three on three need nine, and the business logic is copied into each. Bridge turns that product into a sum. It is a structural design pattern, usually chosen up front, when you can already see two dimensions of change.

1. What Is the Bridge Design Pattern?

The GoF intent is: "Decouple an abstraction from its implementation so that the two can vary independently."

"Abstraction" and "implementation" here do not mean Java's abstract keyword. The abstraction is the high-level behaviour the client uses, such as "pay in three instalments". The implementation is the low-level platform that carries it out, such as a card network or UPI. Both can have their own subclasses.

The abstraction holds a field of the implementor's interface type. That field is the bridge. High-level methods are written in terms of a few primitive implementor operations, like authorize() and capture(), so they work with any implementation passed in. This is composition over inheritance applied to two axes at once, and it keeps each class focused on one dimension (Single Responsibility) and open to new variants on either side (Open/Closed).

2. Key Components

ComponentResponsibilityIn the Basic Example
AbstractionHigh-level API for clients; holds the implementor referencePayment
Refined AbstractionVariants of the high-level behaviourOneTimePayment, EmiPayment
ImplementorInterface of primitive operationsPaymentRail
Concrete ImplementorOne platform's version of those operationsCardRail, UpiRail
ClientPicks an implementor, passes it to an abstraction, and calls the abstractionmain

The client only calls the abstraction. Each abstraction method breaks the request into primitive calls on the implementor it was given. Neither hierarchy references the other's subclasses.

3. When Is Bridge Useful?

  • Feature × platform: payment types (one-time, EMI, subscription) across rails (card, UPI, net banking).
  • Policy × storage: caching strategies (read-through, expiring) over storage engines (hash map, LRU, Redis).
  • Delivery style × broker: direct or batched event publishing over Kafka or RabbitMQ.

4. UML Class Diagram

The diagram shows the Basic Example.

Bridge UML class diagram The abstract Payment class holds a PaymentRail reference, the bridge. OneTimePayment and EmiPayment extend Payment. CardRail and UpiRail implement the PaymentRail interface. «abstract» Payment # rail: PaymentRail + process(amount): String the bridge 1 «interface» PaymentRail + name(): String + authorize(amount): String + capture(authId): String + fee(amount): BigDecimal extends OneTimePayment EmiPayment abstraction side: what the client asks for implements CardRail UpiRail implementation side: how it is carried out
Bridge: two independent hierarchies joined by one reference from the abstraction to the implementor interface.
  1. The left hierarchy is the abstraction: Payment and its subclasses (solid lines, hollow triangle: "extends").
  2. The right hierarchy is the implementation: PaymentRail and its classes (dashed lines: "implements").
  3. The single arrow from Payment to PaymentRail is the bridge: a protected field holding exactly one rail.
  4. No class on the left points to CardRail or UpiRail, so the two sides can grow independently.

5. Step-by-Step Execution Flow

  1. The client creates a rail, for example new UpiRail().
  2. It passes the rail to an abstraction: new EmiPayment(rail, 3). The constructor stores it in the rail field.
  3. The client calls process(3000.00).
  4. EmiPayment applies its own logic: it divides the amount into three instalments.
  5. For each instalment it calls rail.authorize() and rail.capture(). Dynamic dispatch runs the UPI versions.
  6. The combined result goes back to the client, which never touched the rail directly after creating it.

6. Real-World Use Cases

  • E-commerce and payments: checkout flows (one-time, EMI, subscription) over interchangeable payment rails or providers.
  • Banking: statement or alert types over delivery mechanisms such as SFTP drops, email or a partner API.
  • Notifications: message priorities or templates over channels.
  • The JDK: JDBC is the textbook case. Application code is written against the java.sql interfaces (Connection, PreparedStatement), while each vendor's driver supplies the implementation, so changing database means changing the driver, not the code.
  • Spring: the Spring cache abstraction (CacheManager and Cache) lets @Cacheable code run on ConcurrentHashMap, Caffeine or Redis providers, and Spring Cloud Stream separates message handling from Kafka or RabbitMQ binders. Both apply the Bridge idea of a stable API over swappable back ends.

7. Problem Without the Pattern

Payment types and rails combined through inheritance:

PaymentsWithoutBridge.java
import java.math.BigDecimal;
import java.math.RoundingMode;

public class PaymentsWithoutBridge {

    // One subclass per (payment type x payment rail) combination
    abstract static class Payment {
        abstract String process(BigDecimal amount);
    }

    static final class CardOneTimePayment extends Payment {
        String process(BigDecimal amount) { return "card: authorize + capture " + amount; }
    }

    static final class UpiOneTimePayment extends Payment {
        String process(BigDecimal amount) { return "upi: collect request " + amount; }
    }

    static final class CardEmiPayment extends Payment {
        String process(BigDecimal amount) {
            BigDecimal installment = amount.divide(BigDecimal.valueOf(3), 2, RoundingMode.HALF_UP);   // EMI maths copied...
            return "card: 3 x authorize + capture " + installment;
        }
    }

    static final class UpiEmiPayment extends Payment {
        String process(BigDecimal amount) {
            BigDecimal installment = amount.divide(BigDecimal.valueOf(3), 2, RoundingMode.HALF_UP);   // ...into every rail
            return "upi: mandate for 3 x " + installment;
        }
    }

    public static void main(String[] args) {
        Payment[] payments = {new CardOneTimePayment(), new UpiOneTimePayment(), new CardEmiPayment(), new UpiEmiPayment()};
        for (Payment payment : payments) {
            System.out.println(payment.getClass().getSimpleName() + " -> " + payment.process(new BigDecimal("3000")));
        }
        System.out.println("Classes needed: 2 types x 2 rails = " + payments.length + "; add net banking and BNPL: 3 x 3 = 9");
    }
}
Console
CardOneTimePayment -> card: authorize + capture 3000
UpiOneTimePayment -> upi: collect request 3000
CardEmiPayment -> card: 3 x authorize + capture 1000.00
UpiEmiPayment -> upi: mandate for 3 x 1000.00
Classes needed: 2 types x 2 rails = 4; add net banking and BNPL: 3 x 3 = 9
  • Class explosion: types × rails classes, growing multiplicatively.
  • Duplication: the EMI calculation appears once per rail, and so would every bug fix.
  • Tight coupling: each class mixes business rules with rail details.
  • No runtime choice: the rail is fixed by the class name.

8. Solution Using the Pattern

Separate the two questions. A PaymentRail interface answers "how do I move money on this rail?" with small primitives. A Payment hierarchy answers "what kind of payment is this?" and is written only in terms of those primitives. Each payment holds a rail.

Two types and two rails now need four classes in total, and three of each would need six, not nine. The EMI logic exists once and works on every rail. A new rail is one class; a new payment type is one class. The rail can be chosen at runtime from the customer's selection.

9. Bridge Design Pattern in Java: Code Examples

Each example is a single file that runs on Java 21 with java FileName.java.

Basic Example: Payment Types over Payment Rails

Problem: fix section 7 so that each payment type and each rail is written once.

PaymentBridgeDemo.java
import java.math.BigDecimal;
import java.math.RoundingMode;

public class PaymentBridgeDemo {

    // Implementor: low-level operations every payment rail provides
    interface PaymentRail {
        String name();
        String authorize(BigDecimal amount);
        String capture(String authorizationId);
        BigDecimal fee(BigDecimal amount);
    }

    // Concrete implementors
    static final class CardRail implements PaymentRail {
        private int counter = 0;
        public String name() { return "Card"; }
        public String authorize(BigDecimal amount) { return "AUTH-C" + (++counter); }
        public String capture(String authorizationId) { return authorizationId + " captured"; }
        public BigDecimal fee(BigDecimal amount) { return amount.multiply(new BigDecimal("0.02")).setScale(2, RoundingMode.HALF_UP); }
    }

    static final class UpiRail implements PaymentRail {
        private int counter = 0;
        public String name() { return "UPI"; }
        public String authorize(BigDecimal amount) { return "AUTH-U" + (++counter); }
        public String capture(String authorizationId) { return authorizationId + " settled"; }
        public BigDecimal fee(BigDecimal amount) { return new BigDecimal("0.00"); }
    }

    // Abstraction: holds the bridge to a rail and defines high-level behaviour
    abstract static class Payment {
        protected final PaymentRail rail;            // the bridge

        protected Payment(PaymentRail rail) { this.rail = rail; }

        abstract String process(BigDecimal amount);
    }

    // Refined abstractions: written once, work with every rail
    static final class OneTimePayment extends Payment {
        OneTimePayment(PaymentRail rail) { super(rail); }

        String process(BigDecimal amount) {
            String auth = rail.authorize(amount);
            return rail.name() + " one-time " + amount + ": " + rail.capture(auth) + ", fee " + rail.fee(amount);
        }
    }

    static final class EmiPayment extends Payment {
        private final int months;

        EmiPayment(PaymentRail rail, int months) { super(rail); this.months = months; }

        String process(BigDecimal amount) {
            BigDecimal installment = amount.divide(BigDecimal.valueOf(months), 2, RoundingMode.HALF_UP);
            StringBuilder result = new StringBuilder(rail.name() + " EMI " + months + " x " + installment + ":");
            for (int i = 0; i < months; i++) {
                result.append(' ').append(rail.capture(rail.authorize(installment)));
            }
            return result.toString();
        }
    }

    public static void main(String[] args) {
        BigDecimal amount = new BigDecimal("3000.00");
        for (PaymentRail rail : new PaymentRail[] {new CardRail(), new UpiRail()}) {
            System.out.println(new OneTimePayment(rail).process(amount));
            System.out.println(new EmiPayment(rail, 3).process(amount));
        }
    }
}

Important classes and methods

  • PaymentRail exposes primitives only: authorize, capture, fee.
  • Payment.rail is the bridge, set once in the constructor and final.
  • EmiPayment.process() contains the instalment logic and calls the rail three times.

Expected output

Console
Card one-time 3000.00: AUTH-C1 captured, fee 60.00
Card EMI 3 x 1000.00: AUTH-C2 captured AUTH-C3 captured AUTH-C4 captured
UPI one-time 3000.00: AUTH-U1 settled, fee 0.00
UPI EMI 3 x 1000.00: AUTH-U2 settled AUTH-U3 settled AUTH-U4 settled

How it runs

  1. The loop pairs each rail with both payment types: four combinations from four classes.
  2. The card rail charges a 2% fee (60.00); the UPI rail charges none.
  3. EMI splits 3000.00 into three instalments of 1000.00 on either rail.

10. Best Practices and Common Mistakes

Best practices

  • Keep the implementor interface small and primitive; build rich behaviour in the abstraction.
  • Inject the implementor through the constructor and keep the field final.
  • Use a factory or Spring configuration to pick the implementor from the environment.
  • Thread safety: if one abstraction instance is shared, protect its own state (as BatchingPublisher does) and make sure the implementor is safe for concurrent calls too.

Common mistakes

  • Leaking platform details, such as if (rail instanceof UpiRail), into the abstraction.
  • Parallel hierarchies like UpiEmiPayment, which rebuild the explosion.
  • A fat implementor interface that mirrors the abstraction method for method.
  • Overengineering: introducing a bridge when only one dimension actually varies.

11. When to Use and When Not to Use

Use it when you can name two independent reasons for a class to change, when implementations must be swappable at runtime or per deployment, or when you want platform code isolated so it can be tested and replaced on its own.

Avoid it when there is one implementation and no realistic second one, when the variations are not independent (every type needs special handling per platform), or when a single Strategy field already covers the need.

12. Advantages and Disadvantages

Advantages

  • m + n classes instead of m × n.
  • Independent evolution of each side (Open/Closed).
  • Runtime choice of implementation.
  • Platform code isolated from business rules, so each is tested separately.

Disadvantages

  • More up-front design: you must identify the right split.
  • Extra indirection for readers.
  • Lowest common denominator: the implementor interface can only expose what every platform supports.

13. Comparison with Similar Patterns

AspectBridgeStrategyAdapterAbstract Factory
CategoryStructuralBehavioralStructuralCreational
IntentLet two hierarchies vary independentlySwap one algorithmFix an interface mismatchCreate matching families
HierarchiesTwo, both extensibleContext usually has noneAdapter wraps one adapteeFactories and products
TimingDesigned up frontDesigned up frontAdded after the factDesigned up front

If the class holding the reference has its own meaningful subclasses, you have a Bridge; if it is a single context swapping behaviour, it is a Strategy. Use an Adapter to make existing classes fit, and combine Bridge with an Abstract Factory when the right implementor depends on the environment. See also the Decorator, which wraps objects instead of splitting them.

14. Summary

  • The bridge design pattern in Java separates an abstraction hierarchy from an implementation hierarchy.
  • Purpose: avoid m × n subclasses when a class varies in two independent ways.
  • Components: Abstraction, Refined Abstractions, Implementor, Concrete Implementors, Client.
  • The abstraction holds an implementor reference and builds high-level behaviour from its primitives.
  • Used for payments over rails, caches over stores, publishers over brokers, and JDBC.
  • Benefits: fewer classes, runtime swapping and independent evolution.
  • Keep the implementor interface small, and do not add a bridge for a single dimension.

15. Java Design Pattern Interview Questions and Answers

Q1. How do you decide which dimension is the abstraction and which is the implementation?

The abstraction is what the client talks about: the business-level operations and their variants. The implementation is the platform or mechanism those operations rely on, usually expressed as a handful of primitives. A useful test: if one side could be replaced by a different vendor or technology without changing the business meaning, that side is the implementation.

Q2. Can the implementation be switched while the program is running?

Yes. Either create a new abstraction object with the new implementor, or allow replacing the reference. If threads share the object, make the field volatile (or use an AtomicReference) so every thread sees the switch.

private volatile MessageTransport transport;

void switchTo(MessageTransport next) {
    this.transport = Objects.requireNonNull(next);   // visible to all threads
}
Q3. UPI cannot place a pre-authorisation hold, but cards can. How do you model that?

Keep the implementor interface to operations every rail supports, and expose optional abilities explicitly, for example a supportsHold() method or a separate HoldCapable interface. The abstraction checks the capability and chooses another flow, instead of calling a method that throws on some rails.

Q4. How does Bridge reduce the number of tests you need?

Without it, every combination needs its own tests: m × n. With a bridge, test each abstraction once against a fake implementor that records primitive calls, and test each implementor once with a shared contract test. That is m + n test classes, and new combinations need no new tests.

Q5. How would you wire a Bridge in Spring Boot so the implementation follows the environment?

Declare each implementor as a bean guarded by a condition such as @ConditionalOnProperty or @Profile, and inject the implementor interface into the abstraction bean. Changing app.broker=rabbit in configuration then swaps the whole implementation side without code changes.

@Bean
@ConditionalOnProperty(name = "app.broker", havingValue = "kafka")
MessageTransport kafkaTransport() { return new KafkaTransport(); }

@Bean
EventPublisher orderEvents(MessageTransport transport) {
    return new BatchingPublisher(transport, "orders", 100);
}