Introduction

Adapter pattern works as a bridge between two incompatible interfaces. This pattern involves a single class which is responsible to join functionalities of independent or incompatible interfaces. A real life example could be a case of card reader which acts as an adapter between memory card and a laptop. You plugin the memory card into card reader and card reader into the laptop so that memory card can be read via laptop.

Adapter is about creating an intermediary abstraction that translates, or maps, the old component to the new system.

Intent

  • Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.
  • Wrap an existing class with a new interface.

Implementation

The figure below shows a UML class diagram for the Adapter Pattern.


Target defines the domain-specific interface that Client uses. Adapter  adapts the interface Adaptee to the Target interface, where Adaptee defines an existing interface that needs adapting.

Example

Suppose a Bird class with fly() , and makeSound() methods, and  RealDuck class with squeak() method. We will use adapter pattern to make Duck behave like a bird.

// Java implementation of Adapter pattern 
interface Bird 
{ 
  public void fly(); 
  public void makeSound(); 
} 

class Sparrow implements Bird 
{ 
  // Concrete implementation of bird 
  public void fly() 
  { 
    System.out.println("Flying"); 
  } 
  public void makeSound() 
  { 
    System.out.println("Chirp Chirp"); 
  } 
} 

interface Duck 
{ 
  // Target interface 
  public void squeak(); 
} 

class RealDuck implements Duck 
{ 
  public void squeak() 
  { 
    System.out.println("Squeak"); 
  } 
} 

class BirdAdapter implements Duck 
{ 
  // Implement the interface client expects to use. 
  Bird bird; 
  
  public BirdAdapter(Bird bird) 
  { 
    this.bird = bird; 
  } 

  public void squeak() 
  { 
    // translate the methods appropriately 
    bird.makeSound(); 
  } 
} 

class AdapterPattern 
{ 
  public static void main(String args[]) 
  { 
    Sparrow sparrow = new Sparrow(); 
    RealDuck toyDuck = new RealDuck(); 

    // Wrap a bird in a birdAdapter so that it behaves like duck 
    Duck birdAdapter = new BirdAdapter(sparrow); 

    System.out.println("Sparrow..."); 
    sparrow.fly(); 
    sparrow.makeSound(); 

    System.out.println("Duck..."); 
    toyDuck.squeak(); 

    // bird behaving like a toy duck 
    System.out.println("BirdAdapter..."); 
    birdAdapter.squeak(); 
  } 
}