The Adapter Pattern
What you'll learn: You'll discover how the Adapter pattern bridges incompatible interfaces to make existing code work with new systems.
The Core Problem
Imagine you have a class or module with one interface, but your application expects a different one. Rather than rewriting the original code (which might be third-party or legacy), you create an adapter that translates calls between the two interfaces—like a plug adapter that lets your US device work in a European outlet.
How It Works
The Adapter pattern wraps an existing object and exposes a new interface that clients expect. The adapter receives calls in the expected format, translates them, and forwards them to the original object.
// Old logging system you can't change
class LegacyLogger {
log(message) {
console.log(`[OLD] ${message}`);
}
}
// Your app expects this interface
// interface: logInfo(msg), logError(msg)
// Adapter makes LegacyLogger compatible
class LoggerAdapter {
constructor(legacyLogger) {
this.logger = legacyLogger;
}
logInfo(msg) {
this.logger.log(`INFO: ${msg}`);
}
logError(msg) {
this.logger.log(`ERROR: ${msg}`);
}
}
// Usage
const oldLogger = new LegacyLogger();
const adapter = new LoggerAdapter(oldLogger);
adapter.logInfo('System started'); // [OLD] INFO: System started
adapter.logError('Failed'); // [OLD] ERROR: Failed
When to Use It
- Integrating third-party libraries with different APIs
- Working with legacy code you can't modify
- Making multiple similar classes conform to a single interface
- Isolating interface changes from the rest of your codebase
Key Takeaway: The Adapter pattern converts one interface into another, enabling incompatible code to work together without modification—like a translator between two systems that don't speak the same language.