Design Pattern: Bridge

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:

structure

Implementing the Bridge Pattern it becomes:

Bridge

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”.

  1. namespace ConsoleApplication1    
  2. {    
  3.     class Program    
  4.     {    
  5.         static void Main(string[] args)    
  6.         {    
  7.             var hotApi = new HotDrawingImplementor();    
  8.             var coolApi = new CoolDrawingImplementor();    
  9.      
  10.             var hotRectangle = new Rectangle(hotApi);    
  11.             var coolRectangle = new Rectangle(coolApi);    
  12.      
  13.             hotRectangle.Draw();    
  14.             coolRectangle.Draw();    
  15.      
  16.             Console.ReadKey(true);    
  17.         }    
  18.     }    
  19.      
  20.     public abstract class Shape    
  21.     {    
  22.         protected DrawingImplementor implementor;    
  23.      
  24.         public Shape(DrawingImplementor implementor)    
  25.         {    
  26.             this.implementor = implementor;    
  27.         }    
  28.      
  29.         public void Draw()    
  30.         {    
  31.             implementor.Draw();    
  32.         }    
  33.     }    
  34.      
  35.     public class Rectangle : Shape    
  36.     {    
  37.         public Rectangle(DrawingImplementor implementor)    
  38.             : base(implementor)    
  39.         {    
  40.      
  41.         }    
  42.     }    
  43.      
  44.     public class Circle : Shape    
  45.     {    
  46.         public Circle(DrawingImplementor implementor)    
  47.             : base(implementor)    
  48.         {    
  49.         }    
  50.     }    
  51.      
  52.     public abstract class DrawingImplementor    
  53.     {    
  54.         public abstract void Draw();    
  55.     }    
  56.      
  57.     public class CoolDrawingImplementor : DrawingImplementor    
  58.     {    
  59.         public override void Draw()    
  60.         {    
  61.             Console.WriteLine("Drawing cool!");    
  62.         }    
  63.     }    
  64.      
  65.     public class HotDrawingImplementor : DrawingImplementor    
  66.     {    
  67.         public override void Draw()    
  68.         {    
  69.             Console.WriteLine("Drawing hot!");    
  70.         }    
  71.     }    
  72. }  
Output 

    Drawing hot!
    Drawing cool!

If you have a hierarchy like that you might want to consider applying this pattern.


Similar Articles