The Bridge pattern is a structural design pattern in which abstraction is used to separate the interface from the implementation so that the two can be modified independently.
The Bridge pattern is particularly useful when developing code which might need to run on different platforms.
For example, suppose you want to develop a user interface which is intended to run on Windows, but you might in the future want switch to Linux. By using a cross-platform library such as Qt, you can easily switch between one platform and another. In this case, the Qt library is acting as the bridge as it provides an interface which is separate from the platform-dependent implementation.
Example : Drawing
Suppose we want to develop a graphical reporting package e.g. to draw histograms and pie-charts.
We have a raster drawing library which can be used to manipulate pixels in order to create a bitmap.
So we could start by developing some basic geometrical shape classes such as line and circle. Each shape would implement the draw
function using the raster drawing library.
Here is the UML class diagram:
Suppose we now decide we might want to use a vector drawing library instead. The vector drawing library is likely to have a very different API. This would mean that we need to develop vector-drawing equivalents of the Line and Circle class. If we want to keep the old versions of Line and Circle (to keep our options open), we will need four classes:
- RasterCircle
- RasterLine
- VectorCircle
- VectorLine
We can see here how the multiplicity of classes could easily become a cause for concern.
Let’s see how the Bridge pattern can help:
We can see in the diagram how the two class hierarchies are now kept separate. Even though the two drawing libraries are very different, the IDrawingAPI
interface ensures they have a common API. The API either just passes the function call onto the underlying library or, in the case of the raster library, converts the shape into a pixel representation using line and circle drawing algorithms.
With this hierarchy, it is straightforward to add further geometric shapes which can be displayed in either vector or raster form.