lukebevan.com Blog A Computer Science Student from the University of Wolverhampton, UK

22Jul/100

Design Patterns with Java (Adapter Pattern)

The Adapter Pattern is used to convert the interface of a class into another interface the client expects. This design pattern also allows classes to work together even if they have an incompatible interface, which means this pattern can be used to integrate another system with an existing system. Below is the code sample to demonstrate this pattern.


public interface Car {

  public void drive();

  public void navigate();

}


public interface Airplane {

  public void fly();

  public void navigate();

}


public class SmallCar implements Car  {

  public void drive(){

    System.out.println("Small car has moved");

  }

 public void navigate(){

    System.out.println("Small car is now moving in the right direction");

  }

}


public class CarToAirplaneAdapter implements Airplane{

  Car car;

  public CarToAirplaneAdapter(Car car){

    this.car = car;

  }

  public void fly(){

    car.drive();

  }

  public void navigate(){

    car.navigate();

 }

}

CarToAirplaneAdapter implements the methods of the Airplane interface but calls methods on a car object. This adapter also accepts an car object reference in its constructor. The car object is wrapped in an Airplane adapter enabling it to behave like a airplane, this means the code has now been adapted.

Thanks to Head First Design Patterns.



Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

No trackbacks yet.