Adapter Design Pattern in Java
Adapter sits between two classes that do not fit together and translates one interface into the other.
Real life example
A phone charger adapter lets a 3-pin plug work in a 2-pin socket.
When to use
You want to use an old or third-party class, but its methods do not match what your code expects.
Complete Java example
Save this as Main.java, then run javac Main.java and java Main.
public class Main {
public static void main(String[] args) {
Printer p = new PrinterAdapter();
p.print("Hello");
}
}
class OldPrinter { void printText(String t) { System.out.println(t); } } // cannot change this
interface Printer { void print(String t); } // what our app expects
class PrinterAdapter implements Printer {
private OldPrinter old = new OldPrinter();
public void print(String t) { old.printText(t); } // translate the call
}Output
Hello