Adapter Pattern
The Adapter Method Pattern converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.
Bates and Sierra — Head First Design Patterns
Class diagram
/images/posts/design-patterns/adapter_pattern.png
- Client can see only the
Target
interface. Adapter
implements theTarget
interface and is composed with theAdaptee
to which translates or delegates all the requests.Adaptee
gets all the requests delegated by theAdapter
.
##Scenario
##Key Points
- Object composition. The pattern wraps the adaptee with an altered interface and it can use any subclass of the adaptee.
- Bind to an interface. The pattern binds the client to an interface and not to an implementation.
- Adapter.
- Decouple the client from the implemented interface.
- Encapsulate what changes so the client doesn’t have to modify each time needs to operate against a different interface.
- Convert one interface to another so the adapter could wrap one or more adaptee but it would be a bit messy (see Facade Pattern).
- Implement the interface of the type the client is expecting.
- Delegate all the requests to the object it wraps.
- Two ways Adapter. A client could expect old and new interfaces, so the adapter implement both interfaces to support the client.
##Adapter vs. Decorator
- Focus on
- Adapter convert the interface of what it wrap, decorator not change the interface.
- Decorator
- Wrapped many other adapters.
- Add new behaviors.
- Adapter
- Allow clients to use other libraries without changing any code.
##Real World Adapters
- Enumerator. Allow iterate over a collection elements without knowing the collection implementation details.
- Iterator. Like the enumerator but with also the remove method.
Enumerator
is the old fashion interface to iterate the collection elements so an adapter could adapt the old fashion to the new one.
- Target interface.
Iterator
- Adaptee interface.
Enumeration
- The
Adapter
has to implement theTarget
and to compose with theAdaptee
.