The Bridge Pattern
This is the second post in a series of blogposts on Design Patterns. You can read about The Strategy Pattern here.
Intent
- The bridge pattern is used when we want to separate a varying entity from a varying behavior.
- The Gang of Four defines the Bridge Pattern as Separate an abstraction from its implementation so that the two can vary independently.
Example
Assume that you’ve to write a program that draws a rectangle. Since you’ve 2 drawing libraries, you decide to create an abstract class called Rectangle and have the two versions extend this. But then after some time, we need to draw a circle too. So, we decide to create an abstract class called Shape and have both Rectangle and Circle extend it.
The problem with this approach is that scaling the behavior (drawing a line) also depends on scaling the entitities (rectangle, circle etc).
Structure
In this design pattern, the AbstractBehavior is passed as a parameter to AbstractEntity. This gives the AbstractBehavior to vary independently of the AbstractEntity.
A way to achieve this procedurally is through nested branching statements - you can clearly see why this doesn’t scale.
Code
Kaushik Rangadurai
Code. Learn. Explore