Problem Statement
When integrating two systems or components that have incompatible interfaces, direct communication fails. This causes errors or forces rewriting existing code, increasing time and cost.
┌─────────────┐ ┌───────────────┐ ┌─────────────┐ │ Client │─────▶│ Adapter │─────▶│ Adaptee │ │ (expects │ │ (translates │ │ (incompatible│ │ Target API) │ │ interface) │ │ interface) │ └─────────────┘ └───────────────┘ └─────────────┘
This diagram shows the client calling the adapter, which translates calls to the adaptee's incompatible interface.
### Before Adapter (incompatible interface) class OldPrinter: def print_text(self, text): print(f"Old Printer: {text}") class Client: def __init__(self, printer): self.printer = printer def print(self, message): # Expects method named 'print' self.printer.print(message) printer = OldPrinter() client = Client(printer) # This will fail because OldPrinter has no 'print' method # client.print("Hello") ### After Adapter class PrinterAdapter: def __init__(self, old_printer): self.old_printer = old_printer def print(self, message): self.old_printer.print_text(message) printer = OldPrinter() adapter = PrinterAdapter(printer) client = Client(adapter) client.print("Hello") # Works correctly
Adapter pattern in system design?class Adaptee {
String specificRequest() { return "Adaptee response"; }
}
interface Target {
String request();
}
class Adapter implements Target {
private Adaptee adaptee = new Adaptee();
public String request() {
return adaptee.specificRequest();
}
}
public class Main {
public static void main(String[] args) {
Target target = new Adapter();
System.out.println(target.request());
}
}interface Target {
void request();
}
class Adaptee {
void specificRequest() { System.out.println("Adaptee called"); }
}
class Adapter implements Target {
Adaptee adaptee = new Adaptee();
public void request() {
specificRequest();
}
}processLegacyPayment(), but the platform expects processPayment(). How should you apply the Adapter pattern to solve this?processPayment(), but legacy system only has processLegacyPayment().processLegacyPayment() to adapt calls without changing legacy code.Pass the test and this pattern moves unknown