You have an existing class with an interface that doesn't match what your client expects. You can't modify the existing class. Adapter wraps it with the interface your client needs.
// ─── EXAMPLE 1 ──────────────────────────────────────────────────────────────
// WHAT WE ARE IMPLEMENTING:
// A generic notification system integrating a legacy third-party SMS API.
//
// WHERE THE PATTERN FITS IN:
// TwilioAdapter is the Adapter. It implements the target client interface
// NotificationChannel and wraps the Adaptee TwilioService.
// ────────────────────────────────────────────────────────────────────────────
// --- Target interface (what the client expects) ---
interface NotificationChannel {
boolean send(String recipient, String message);
}
// --- Adaptee (incompatible third-party library) ---
class TwilioService {
public String dispatchSms(String phoneNumber, String text) {
System.out.println(" [Twilio] Dispatching to " + phoneNumber + ": " + text);
return "msg_" + System.currentTimeMillis();
}
}
// --- Adapter ---
class TwilioAdapter implements NotificationChannel {
private final TwilioService twilioService;
public TwilioAdapter(TwilioService twilioService) {
this.twilioService = twilioService;
}
public boolean send(String recipient, String message) {
String msgId = twilioService.dispatchSms(recipient, message);
return msgId != null;
}
}
// --- Client ---
class NotificationService {
private final NotificationChannel channel;
public NotificationService(NotificationChannel channel) {
this.channel = channel;
}
public void alert(String recipient, String message) {
if (channel.send(recipient, message)) {
System.out.println(" Alert sent successfully to " + recipient);
}
}
}
public class Main {
public static void main(String[] args) {
NotificationChannel adapter = new TwilioAdapter(new TwilioService());
NotificationService service = new NotificationService(adapter);
service.alert("+1234567890", "System is down!");
}
}