Card 02/ 05
Bridge vs Adapter
Both put an interface between two classes; one is designed in before, the other added after.
Bridge and Adapter both place an interface between a class and the code that does its work, and the difference is when and why that interface appears. A bridge is designed before either side is written, so that two hierarchies can grow independently. An adapter is added afterwards, to make a class that already exists fit an interface it was never written for. This card compares the two and their diagrams.
| Question | Bridge | Adapter |
|---|---|---|
| When is it introduced? | At design time, before the classes exist | After the fact, when an existing class does not fit |
| Who owns both sides? | The same team designs both hierarchies | The adaptee often belongs to someone else |
| What varies? | Both sides, each with its own subclasses | Usually nothing; it joins one existing class to one interface |
| What does it fix? | Classes multiplying as two dimensions combine | An interface mismatch |
The bridge diagram has a hierarchy on each side of the reference, and the abstraction's interface was designed with the implementor's in mind. The adapter diagram has a single class on each side, and the adaptee's method, specificRequest, has a name that nobody chose for this client.
A design can start with an adapter and grow into a bridge. A first payment gateway is adapted to the shop's interface; when a second and third gateway arrive, and the shop adds a second kind of payment, the interface between them has become a bridge with adapters as its concrete implementors.
← → move through sections and cards