Main Page | See live article | Alphabetical index

Bridge pattern

The bridge pattern is a design pattern used in software engineering

The bridge design pattern is meant to "decouple an abstraction from its implementation so that the two can vary independently" (Gamma et. al.). The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.

When a class varies often, the features of object-oriented programming become very useful because changes to a program's code can be made easily with minimal prior knowledge about the program. The bridge pattern is useful when not only the class itself varies often but also what the class does. The class itself can be thought of as the abstraction and what the class can do as the implementation.

When the abstraction and implementation are separated they can vary independently. A good example use of the bridge design pattern comes from Design Patterns Explained: A New Perspective on Object-Oriented Design by Shalloway and Trott. Say you have an abstraction, shapes. You want to have many types of shapes and each with its own properties but there are things that all shapes do. One thing you want all shapes to do is draw themselves. However, drawing graphics to a screen can sometimes be dependent on different graphics implementations or operating systems. You want your shapes to be able to be drawn on many types of systems but having the shape itself implement them all or modifying the shape class to work with different architechtures. The bridge helps by allowing you to create new classes that provide the drawing implementation. The, abstraction, shape class provides methods for getting the size or properties of a shape while the, implementation, drawing class provides an interface for drawing graphics. Now if a new shape needs to be created or you want to draw your shapes on a new graphics API then it is very easy to add a new class that implements the features you need.

References