Today I’m going to write some examples of Bridge. The design
pattern not the
game. Bridge is a structural
pattern that decouples abstraction from the implementation of some component
so the two can vary independently. The bridge pattern can also be thought of as
two layers of abstraction.
Bridge pattern is useful in times when you need to switch between multiple
implementations at runtime. Another great case for using bridge is when you
need to couple pool of interfaces with a pool of implementations (e.g. 5
different interfaces for different clients and 3 different implementations for
different platforms). You need to make sure, that there’s a solution for every
type of client on each platform. This could lead to very large number of
classes in the inheritance hierarchy doing virtually the same thing. The
implementation of the abstraction is moved one step back and hidden behind
another interface. This allows you to outsource the implementation into another
(orthogonal) inheritance hierarchy behind another interface. The original
inheritance tree uses implementation through the bridge interface. Let’s have a
look at diagram in Figure 1.
As you can see, there are two orthogonal inheritance hierarchies. The first
one is behind ImplementationInterface . This implementation is injected
using aggregation through Bridge class into the second hierarchy under the
AbstractInterface . This allows having multiple cases coupled with multiple
underlying implementations. The Client then uses objects through
AbstractInterface . Let’s see it in code.
The Bridge pattern is very close to the
Adapter by it’s structure, but there’s a huge difference in
semantics. Bridge is designed up-front to let the abstraction and the
implementation vary independently. Adapter is retrofitted to make unrelated
classes work together .