Adapter

Intent

Problem

An "off the shelf" component offers compelling functionality that you would like to reuse, but its "view of the world" is not compatible with the philosophy and architecture of the system currently being developed.

Structure Summary

Structure category:  
wrapper
Similar patterns:   Facade   Proxy

Discussion

Reuse has always been painful and elusive. One reason has been the tribulation of designing something new, while reusing something old. There is always something not quite right between the old and the new. It may be physical dimensions or misalignment. It may be timing or synchronization. It may be unfortunate assumptions or competing standards.

It is very similar to the electrical engineering activity of "impedance matching" – adapting the input resistance, inductance, and capacitance of a load to match the output impedance of a source.

It is like the problem of inserting a new three-prong electrical plug in an old two-prong wall outlet – some kind of adapter or intermediary is necessary.

Adapter is about creating an intermediary abstraction that translates, or maps, the old component to the new system. Clients call methods on the Adapter object which redirects them into calls to the legacy component. This strategy can be implemented either with inheritance or with aggregation.

Adapter functions as a wrapper or modifier of an existing class. It provides a different or translated view of that class.

Structure

Below, a legacy Rectangle component's display() method expects to receive "x, y, w, h" parameters. But the client wants to pass "upper left x and y" and "lower right x and y". This incongruity can be reconciled by adding an additional level of indirection – i.e. an Adapter object.

The Adapter could also be thought of as a "wrapper".

Example

The Adapter pattern allows otherwise incompatible classes to work together by converting the interface of one class into an interface expected by the clients. Socket wrenches provide an example of the Adapter. A socket attaches to a ratchet, provided that the size of the drive is the same. Typical drive sizes in the United States are 1/2" and 1/4". Obviously, a 1/2" drive ratchet will not fit into a 1/4" drive socket unless an adapter is used. A 1/2" to 1/4" adapter has a 1/2" female connection to fit on the 1/2" drive ratchet, and a 1/4" male connection to fit in the 1/4" drive socket. [Michael Duell, "Non-software examples of software design patterns", Object Magazine, Jul 97, p54]

Check list

  1. Identify the players: the component(s) that want to be accommodated (i.e. the client), and the component that needs to adapt (i.e. the adaptee).
  2. Identify the interface that the client requires.
  3. Design a "wrapper" class that can "impedance match" the adaptee to the client.
  4. The adapter/wrapper class "has a" instance of the adaptee class.
  5. The adapter/wrapper class "maps" the client interface to the adaptee interface.
  6. The client uses (is coupled to) the new interface

Before and after

BeforeAfter
// BEFORE - Because the interface between Line and
// Rectangle objects is incapatible, the user has to
// recover the type of each shape and manually supply
// the correct arguments.

// AFTER - The Adapter's "extra level of indirection"
// takes care of mapping a user-friendly common interface
// to legacy-specific peculiar interfaces.

class LegacyLine {
   public void draw( int x1, int y1, int x2, int y2 ) {
      System.out.println( "line from (" + x1 + ',' + y1
                    + ") to (" + x2 + ',' + y2 + ')' );
}  }
class LegacyRectangle {
   public void draw( int x, int y, int w, int h ) {
      System.out.println( "rectangle at (" + x + ',' + y
           + ") with width " + w + " and height " + h );
}  }

public class AdapterDemo {
   public static void main( String[] args ) {
      Object[] shapes = { new LegacyLine(),
                          new LegacyRectangle() };
      // A begin and end point from a graphical editor
      int x1 = 10, y1 = 20;
      int x2 = 30, y2 = 60;
      for (int i=0; i < shapes.length; ++i)
         if (shapes[i].getClass().getName()
                    .equals("LegacyLine"))
            ((LegacyLine)shapes[i]).draw( x1, y1, x2, y2 );
         else if (shapes[i].getClass().getName()
                    .equals("LegacyRectangle"))
            ((LegacyRectangle)shapes[i]).draw(
                  Math.min(x1,x2), Math.min(y1,y2),
                  Math.abs(x2-x1), Math.abs(y2-y1) );
}  }

// line from (10,20) to (30,60)
// rectangle at (10,20) with width 20 and height 40
  
class LegacyLine {
   public void draw( int x1, int y1, int x2, int y2 ) {
      System.out.println( "line from (" + x1 + ',' + y1
                    + ") to (" + x2 + ',' + y2 + ')' );
}  }
class LegacyRectangle {
   public void draw( int x, int y, int w, int h ) {
      System.out.println( "rectangle at (" + x + ',' + y
           + ") with width " + w + " and height " + h );
}  }

interface Shape {
   void draw( int x1, int y1, int x2, int y2 );
}

class Line implements Shape {
   private LegacyLine adaptee = new LegacyLine();
   public void draw( int x1, int y1, int x2, int y2 ) {
      adaptee.draw( x1, y1, x2, y2 );
}  }

class Rectangle implements Shape {
   private LegacyRectangle adaptee = new LegacyRectangle();
   public void draw( int x1, int y1, int x2, int y2 ) {
      adaptee.draw( Math.min(x1,x2), Math.min(y1,y2),
                    Math.abs(x2-x1), Math.abs(y2-y1) );
}  }

public class AdapterDemo {
   public static void main( String[] args ) {
      Shape[] shapes = { new Line(), new Rectangle() };
      // A begin and end point from a graphical editor
      int x1 = 10, y1 = 20;
      int x2 = 30, y2 = 60;
      for (int i=0; i < shapes.length; ++i)
         shapes[i].draw( x1, y1, x2, y2 );
}  }

// line from (10,20) to (30,60)
// rectangle at (10,20) with width 20 and height 40
  

Rules of thumb

Adapter makes things work after they're designed; Bridge makes them work before they are. [GoF, p219]

Bridge is designed up-front to let the abstraction and the implementation vary independently. Adapter is retrofitted to make unrelated classes work together. [GoF, p161]

Adapter provides a different interface to its subject. Proxy provides the same interface. Decorator provides an enhanced interface. [GoF. p216]

Adapter is meant to change the interface of an existing object. Decorator enhances another object without changing its interface. Decorator is thus more transparent to the application than an adapter is. As a consequence, Decorator supports recursive composition, which isn't possible with pure Adapters. [GoF, 149]

Facade defines a new interface, whereas Adapter reuses an old interface. Remember that Adapter makes two existing interfaces work together as opposed to defining an entirely new one. [GoF, pp219]