Apr 232013
 

The adapter pattern is aka a wrapper. This makes sense when you see the code. It’s used to ‘adapt’ one interface to another interface. Not that you would ever design a system this way, but it serves to demonstrate the pattern; maybe you are maintaining some code poorly written code and you need to adapt it to work with your well designed code; example code below:

 

Existing interface and concrete class:

interface Child {

  public void babble();

  public void crawl();

}

 

class Toddler implements child {

  public Toddler() {
  }

  public void babble() {
    System.out.println("babble, babble, babble");
  }

  public void crawl() {
    System.out.println("Crawl, crawl, crawl");
  }
} // end of class

Okay, now you have to adapt it to the Human interface via the ChildAdapter concrete class.

interface Human {

  public void speak();

  public void walk();
}

 

class ChildAdapter implements Human {

  private Child child;

  public ChildAdapter (Child child) {
    this.child = child;
  }

  public void speak() {
    child.babble();
  }

  public void walk() {
    child.crawl();
  }
} // end of class
 Posted by at 8:12 am