The Bridge Design Pattern allows you to decouple the implementation from the abstraction. In other words we can have the implementation separated from our classes and reuse them rather than implementing another hierarchy level.
One simple example mentioned on Stack Overflow is the following structure:
Implementing the Bridge Pattern it becomes:
This simple example explains what it is and shows you why you would want it. But what about a more realistic world example? Well, we could, for example, rename the “Color” stuff to “DrawingApi”.
- namespace ConsoleApplication1
- {
- class Program
- {
- static void Main(string[] args)
- {
- var hotApi = new HotDrawingImplementor();
- var coolApi = new CoolDrawingImplementor();
-
- var hotRectangle = new Rectangle(hotApi);
- var coolRectangle = new Rectangle(coolApi);
-
- hotRectangle.Draw();
- coolRectangle.Draw();
-
- Console.ReadKey(true);
- }
- }
-
- public abstract class Shape
- {
- protected DrawingImplementor implementor;
-
- public Shape(DrawingImplementor implementor)
- {
- this.implementor = implementor;
- }
-
- public void Draw()
- {
- implementor.Draw();
- }
- }
-
- public class Rectangle : Shape
- {
- public Rectangle(DrawingImplementor implementor)
- : base(implementor)
- {
-
- }
- }
-
- public class Circle : Shape
- {
- public Circle(DrawingImplementor implementor)
- : base(implementor)
- {
- }
- }
-
- public abstract class DrawingImplementor
- {
- public abstract void Draw();
- }
-
- public class CoolDrawingImplementor : DrawingImplementor
- {
- public override void Draw()
- {
- Console.WriteLine("Drawing cool!");
- }
- }
-
- public class HotDrawingImplementor : DrawingImplementor
- {
- public override void Draw()
- {
- Console.WriteLine("Drawing hot!");
- }
- }
- }
Output
If you have a hierarchy like that you might want to consider applying this pattern.