The Adapter Pattern allows incompatible interfaces to collaborate by providing a wrapper that translates requests from one interface to another.
It helps integrate existing classes or modules without modifying their original code.
- Compatibility: Lets incompatible interfaces work together.
- Reusability: Enables reuse of existing classes or components.
- Single Responsibility Principle: Keeps translation logic separate from business logic.
- You want to reuse existing code with an incompatible interface.
- Integrating legacy code or third-party libraries that don't match your interface.
class OldPrinter {
oldPrint(text: string): void {
console.log(`Old Printer printing: ${text}`);
}
}
interface Printer {
print(text: string): void;
}
class PrinterAdapter implements Printer {
private oldPrinter: OldPrinter;
constructor(oldPrinter: OldPrinter) {
this.oldPrinter = oldPrinter;
}
print(text: string): void {
this.oldPrinter.oldPrint(text);
}
}
const oldPrinter = new OldPrinter();
const adapter: Printer = new PrinterAdapter(oldPrinter);
adapter.print("Hello, Adapter Pattern!");
Old Printer printing: Hello, Adapter Pattern!
The Adapter Pattern bridges the gap between incompatible interfaces, enhancing compatibility and reuse of existing components without modifying their original implementations.