Adapter Pattern

Intent: Convert the interface of some class b into an interface a that some client class c understands. The AdapterPattern 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 AdapterPattern and the BridgePattern are specific instances of JimCoplien's EnvelopeLetter idiom. Or of the HandleBodyPattern.


The description above talks about Adapter as being a way to wrap an object in an incompatible interface. In reality, the AdapterPattern 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 AdapterPattern repeatedly to implement the LawOfDemeter; to avoid having clients of a class coupled to the internal structure of the class. --DaveOrme



 /* 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: BridgePattern, DecoratorPattern, RetrofitInterfacePattern, ProxyPattern, DesignPatterns, HandleBodyPattern, TwoWayAdapter

CategoryPattern, CategoryStructuralPatterns, CategoryInterface


EditText of this page (last edited October 14, 2014) or FindPage with title or text search