View RSS Feed

My Java Tips

Adapter design pattern

Rate this Entry
by , 11-20-2011 at 07:10 PM (2023 Views)
A Adapter design pattern is Structural design pattern. It is also called as wrapper pattern or just a wrapper. Some classes could not work together because of incompatible interfaces. An adapter allows classes to work together by wrapping its own interface around that of an already existing class. The adapter also handles the logic necessary to transform data into an appropriate form.

The adapter design pattern is useful in circumstances where an already existing class provides some or all of the services you require but does not use the interface you require. The adapter design pattern adapts one interface for a class into one that a client expects.

The adapter patterns are of two types

Object Adapter pattern: In this type of adapter pattern, the adapter contains an OBJECT of the class it wraps. In such a situation, the adapter makes calls to the instance of the wrapped object.

Class Adapter pattern: It requires multiple multiple inheritance. As Java that does not support multiple inheritance, the Class Adapter pattern cannot be used in Java.

Choosing between Facade and Adapter

There is a definite difference between the Facade and Adapter. A facade is a better choice when one wants an easier or simpler interface to work with. Where as the Adapter Design Pattern is used when wrapper must support a polymorphic behavior and wrapper must respect a particular interface.

The example below demonstrates the use of Adapter Design Pattern. The adaptee class is DoubleLinkedList. The client class DoubleLinkedListPushPull instanciates adapter objects.
Java Code:
interface PushPull
  void push (T o);
  T pop ();
  T top ();

//adaptee class
class DoubleLinkedList
  public void insert (DNode pos, T o) { // code to insert}
  public void remove (DNode pos) { // code to remove}

  public void insertHead (T o) { // code to insert head}
  public void insertTail (T o) { // code to insert tail}

  public T removeHead () { // code to remove head}
  public T removeTail () { // code to remove tail}

  public T getHead () { // code to get head}
  public T getTail () { // code to tail}

class DoubleLinkedListPushPull extends DoubleLinkedList implements PushPull
  public void push (T o) {
    insertTail (o);

  public T pop () {
    return removeTail ();

  public T top () {
    return getTail ();

Submit "Adapter design pattern" to Facebook Submit "Adapter design pattern" to Digg Submit "Adapter design pattern" to Submit "Adapter design pattern" to StumbleUpon Submit "Adapter design pattern" to Google