notes / design-patterns / structural / adapter.md · 2026-03 · 2 min
# Adapter Pattern
### Convert the interface of a class into another interface that clients expect.
This means that an adapter allows two incompatible interfaces to work together without modifying their existing code.
## 🍽️ Imagine a restaurant:
### ❌ Bad Design
A new coffee machine arrives, but:
- It uses a different plug
- It doesn’t fit existing sockets
👉 You cannot use it with your current system
### ✅ Good Design with Adapter Pattern
You use an adapter plug:
- Converts the plug type
- Makes the machine compatible
##### You don’t change the machine!
##### You don’t change the socket!
##### You just add an adapter!
## 🧑💻 In software:
### ❌ Bad Design
class OldPrinter {
void printText(String text) {
System.out.println(text);
}
}
class Client {
void print(OldPrinter printer) {
printer.printText("Hello");
}
}
Now imagine a new printer with a different interface:
class NewPrinter {
void printDocument(String doc) {
System.out.println(doc);
}
}
👉 Client cannot use NewPrinter without modification
### ✅ Good Design with Adapter Pattern
interface Printer {
void print(String text);
}
class OldPrinterAdapter implements Printer {
private OldPrinter oldPrinter;
OldPrinterAdapter(OldPrinter oldPrinter) {
this.oldPrinter = oldPrinter;
}
public void print(String text) {
oldPrinter.printText(text);
}
}
class NewPrinterAdapter implements Printer {
private NewPrinter newPrinter;
NewPrinterAdapter(NewPrinter newPrinter) {
this.newPrinter = newPrinter;
}
public void print(String text) {
newPrinter.printDocument(text);
}
}
class Client {
void print(Printer printer) {
printer.print("Hello");
}
}
Now both old and new printers can be used without changing the client code.