Video in progress
What problem does the Adapter pattern solve?
An Adapter connects two interfaces that don't fit together: it "wraps" an existing class in the interface you expect, without changing the class. It's the same idea as a socket adapter.
📖 Answer
The typical case: your code expects a SmsGateway interface, and the new provider gives you an SDK with completely different methods that you can't change.
// our interface
public interface SmsGateway {
void send(String phone, String text);
}
// the external SDK, can't be changed
public class ProviderClient {
public Response sendMessage(MessageRequest req) { ... }
}
// the adapter
public class ProviderSmsAdapter implements SmsGateway {
private final ProviderClient client;
public ProviderSmsAdapter(ProviderClient client) { this.client = client; }
@Override
public void send(String phone, String text) {
var req = new MessageRequest("+998" + phone, text);
client.sendMessage(req);
}
}
The rest of the code only sees SmsGateway. If the provider changes, you write a new adapter and that's it.
Examples in the JDK: Arrays.asList() presents an array as a List, and InputStreamReader adapts a stream of bytes to a stream of characters.
Sign up to mark studied questions and save your progress.