Adapter pattern
easy 50 minThe Adapter pattern makes an existing class fit the interface that its client expects, without changing either of them.
Watch lesson4:39
When it comes up
The moments this idea belongs in a design interview, and the moments it does not.
Listen
Words that announce it
| They say | Think |
|---|---|
| "We already have a library for this" | Adaptee exists, find the target |
| "Support several providers" | One interface, one adapter each |
| "The old system must keep running" | Adapter, maybe two-way |
| "The vendor may change" | No vendor type outside the adapter |
| "Their API returns error codes" | Translate failures |
| "We can not change that class" | Wrap it |
Decide
One question, three answers
The interviewer gives you a vendor's class with sendSms(String number, byte[] text, int flags) and asks for notifications by SMS and mail. What do you write first?
BreaksCalls to sendSms in the order service
- How
- Direct use, flags included.
- Limit
- The vendor's flags are now business code. Mail needs a second copy of everything.
- Choose when
- Never.
WorksAn interface with the same method
- How
interface SmsSender { sendSms(number, bytes, flags) }- Limit
- Mail has no flags and no number. The interface is the vendor in disguise.
- Choose when
- Only if the one aim is a fake for tests.
StrongNotifier.send(Person, Message) and one adapter per channel
- How
- The target says what the order service wants. Each adapter finds its own address and format.
- Limit
- You must decide what a message is.
- Choose when
- Always when more than one channel is named.