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
- Client can see only the
Targetinterface and is composed with the
Adapteeto which translates or delegates all the requests.
Adapteegets all the requests delegated by the
- 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.
- 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.
- Wrapped many other adapters.
- Add new behaviors.
- 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.
- Adaptee interface.
Adapterhas to implement the
Targetand to compose with the