Design Patterns Explained: The Bridge Pattern
This chapter continues the discussion of design patterns with the Bridge pattern. The Bridge pattern is quite a bit more complex than the other patterns you have learned. It is also much more useful.
- Provides an example to help you derive the Bridge pattern. I go into great detail to help you learn this pattern.
- Presents the key features of the pattern.
- Presents some observations on the Bridge pattern from my own practice.
Introducing the Bridge Pattern
According to the Gang of Four, the intent of the Bridge pattern is to “decouple an abstraction from its implementation so that the two can vary independently.”1
I remember exactly what my first thoughts were when I read this: Huh?
And then: How come I understand every word in this sentence, but I have no idea what it means?
I knew that
- Decouple means to have things behave independently from each other or at least explicitly state what the relationship is.
- Abstraction is how different things are related to each other conceptually.
And I thought that implementations were the way to build the abstractions; but I was confused about how I was supposed to separate abstractions from the specific ways that implemented them.
It turns out that much of my confusion was due to misunderstanding what implementations meant. Implementations here means the objects that the abstract class and its derivations use to implement themselves (not the derivations of the abstract class, which are called concrete classes). To be honest, even if I had understood it properly, I am not sure how much it would have helped. The concept expressed in this sentence is just hard to understand at first.
If you are also confused about the Bridge pattern at this point, that is okay. If you understand the stated intent, you are that much ahead.
It is a challenging pattern to learn because it is so powerful.
The Bridge pattern is one of the toughest patterns to understand in part because it is so powerful and applies to so many situations. It also goes against a common tendency to handle special cases with inheritance. However, it is also an excellent example of following two of the mandates of the design pattern community: “Find what varies and encapsulate it” and “Favor aggregation over class inheritance” (as you will see).