Java Design Patterns Adapter Patterns

Introduction

Adapter Patterns convert the interface into another interface for clients.

The adapter pattern allows classes with incompatible interfaces to work together.

Use case

  • Create adapter class to link various types of objects.

Example

class Rect {/*w  w  w  . java  2  s  . com*/
   public double height;
   public double width;
}

class Triangle {
   public double base;
   public double height;

   public Triangle(int b, int h) {
      this.base = b;
      this.height = h;
   }
}

class Calculator {
   Rect rectangle;

   public double getArea(Rect r) {
      rectangle = r;
      return rectangle.height * rectangle.width;
   }
}

class CalculatorAdapter {
   Calculator calculator;
   Triangle triangle;

   public double getArea(Triangle t) {
      calculator = new Calculator();
      triangle = t;
      Rect r = new Rect();
      // Area of Triangle=0.5*base*height
      r.height = triangle.base;
      r.width = 0.5 * triangle.height;
      return calculator.getArea(r);
   }

}

public class Main {
   public static void main(String[] args) {
      CalculatorAdapter cal = new CalculatorAdapter();
      Triangle t = new Triangle(20, 10);
      System.out.println("Area of Triangle is :" + cal.getArea(t));
   }
}



PreviousNext

Related