Tuesday, April 24, 2012

Structural Patterns - 2.Bridge Pattern

There are scenarios where we may need to deal with different combinations of abstractions and their implementations.

Bridge pattern helps us to seperate/decouple the abstraction and its implementation. We can use composition in order to associate an abstraction to a particular implementation. This will help us to design an extensible application.

Here, the abstractions and implementations where nowhere related to each other.

For example, We are having some abstractions of Pen like fountain pen, ball point pen,etc. As an implementation we can have some documents or contents like poem,essay,etc can be written out of a Pen.

Here, we compose Content to the Pen class so that we can use any type of pen to draft any type of content. The following class diagram explains this pattern,







Code to associate an abstraction to an implementation dynamically,


  Pen[] pens=new Pen[]{new BallPointPen(new Essay()),
                                                                 new FountainPen(new Poem())};
  for(Pen pen:pens){  
         System.out.println(pen.write());
  }

In the above code snippet, we dynamically associate the Essay and Poem instances to BallPointPen and FountainPen instances respectively.


In the BallPointPen/FountainPen class, we can handle this association as follows,


            public BallPointPen(Content content) {  
                      this.content=content;
            }
           @Override
           public String write() {  
                      return content.createContent()+" with BallPoint Pen";
           }

No comments:

Post a Comment