Java Design Patterns Bridge Patterns

Introduction

Bridge Patterns decouple an abstraction from its implementation.

Example

interface Printable {
   void print(int border);
}

class RedColor implements Printable {
   @Override//from  w  w  w  . j av  a2 s.  co m
   public void print(int border) {
      System.out.println("Red color with " + border + " inch border");

   }
}

class GreenColor implements Printable {
   @Override
   public void print(int border) {
      System.out.println("Green color with " + border + " inch border.");

   }
}

abstract class Shape {
   protected Printable color;

   protected Shape(Printable c) {
      this.color = c;
   }

   abstract void drawShape(int border);

   abstract void modifyBorder(int border, int increment);
}

class Triangle extends Shape {
   protected Triangle(Printable c) {
      super(c);
   }

   @Override
   void drawShape(int border) {
      color.print(border);
   }

   @Override
   void modifyBorder(int border, int increment) {
      border = border * increment;
      drawShape(border);
   }
}

class Rectangle extends Shape {
   public Rectangle(Printable c) {
      super(c);
   }

   @Override
   void drawShape(int border) {
       color.print(border);
   }

   @Override
   void modifyBorder(int border, int increment) {
       border = border * increment;
      drawShape(border);
   }
}

public class Main {
   public static void main(String[] args) {
       Printable green = new GreenColor();
      Shape triangleShape = new Triangle(green);
      triangleShape.drawShape(20);
      triangleShape.modifyBorder(20, 3);

      Printable red = new RedColor();
      Shape rectangleShape = new Rectangle(red);
      rectangleShape.drawShape(50);
 
      rectangleShape.modifyBorder(50, 2);

   }
}



PreviousNext

Related