patternModeratepending
Adapter pattern -- make incompatible interfaces work together
Viewed 0 times
adapterwrapperinterface translationdecouplinglibrary swapfacade
Problem
Need to use a library or service that has a different interface than what your code expects. Changing either side is not possible or desirable.
Solution
Create a thin wrapper (adapter) that translates between the two interfaces. The adapter implements the expected interface and delegates to the actual implementation. This decouples your code from specific library APIs.
Code Snippets
Adapter pattern for logger abstraction
// Your code expects this interface
interface Logger {
info(msg: string, meta?: object): void;
error(msg: string, meta?: object): void;
warn(msg: string, meta?: object): void;
}
// But you're using Winston which has a different API
import winston from 'winston';
class WinstonAdapter implements Logger {
private logger: winston.Logger;
constructor() {
this.logger = winston.createLogger({ /* config */ });
}
info(msg: string, meta?: object) { this.logger.info(msg, meta); }
error(msg: string, meta?: object) { this.logger.error(msg, meta); }
warn(msg: string, meta?: object) { this.logger.warn(msg, meta); }
}
// Later: swap to Pino without changing any business code
class PinoAdapter implements Logger {
private logger = pino();
info(msg: string, meta?: object) { this.logger.info(meta, msg); }
// ... note: Pino has different argument order!
}Revisions (0)
No revisions yet.