Adapter Pattern

Intent: Convert the interface of some class b into an interface a that some client class c understands. The Adapter Pattern lets classes with incompatible interfaces work together. This is sometimes called a wrapper because an adapter class wraps the implementation of another class in the desired interface. This pattern makes heavy use of delegation where the delegator is the adapter (or wrapper) and the delegate is the class being adapted.

One could say that both the Adapter Pattern and the Bridge Pattern are specific instances of Jim Coplien's Envelope Letter idiom. Or of the Handle Body Pattern.


The description above talks about Adapter as being a way to wrap an object in an incompatible interface. In reality, the Adapter Pattern can be used for much more than that. Its principal feature is that it provides a way for an object to permit access to its internals in such a way that clients are not coupled to the structure of those internals. The Eclipse code base applies this characteristic of the Adapter Pattern repeatedly to implement the Law Of Demeter; to avoid having clients of a class coupled to the internal structure of the class. --Dave Orme


www.castle-cadenza.demon.co.uk (where it is called Wrapper rather than Adapter).


/* Java code sample */

interface Stack<T> { public void push(T t); public T pop(); public T top(); }

/* DoubleLinkedList */ class DList<T> { public void insert(DNode pos, T t); public void remove(DNode pos, T t);

public void insertHead(T t); public void insertTail(T t);

public T removeHead(); public T removeTail();

public T getHead(); public T getTail(); }

/* Adapt DList class to Stack interface */ class DListImpStack<T> extends DList<T> implements Stack<T> { public void push(T t) { insertTail(t); }

public T pop() { return removeTail(); }

public T top() { return getTail(); } };

Here is the Adapter from the above example with composition:

/* Adapter using composition */

class DListToStackAdapter<T> implements Stack<T> { private DList<T> m_List;

public DListToStackAdapter(DList<T> m_List) { this.m_List = m_List; }

public void push(T t) { m_List.insertTail(t); }

public T pop() { return m_List.removeTail(); }

public T top() { return m_List.getTail(); }

}


See original on c2.com