A practical example of the Adapter pattern is bridging a modern logging framework with an outdated logging module during a system migration, without modifying either the new framework or the legacy code.
Key Points: • The application's current code depends on a modern Logger interface (e.g., a method like log(String message)). • A legacy module only knows how to call an old-style method, such as writeToLogFile(String entry). • An adapter class implements the modern Logger interface and internally delegates to the legacy method, translating the call. • Neither the legacy module nor the rest of the application needs to change; only the adapter class is new. • This pattern is especially common during incremental migrations, where old and new systems must coexist temporarily.
Example: A LegacyLoggerAdapter implements the modern Logger interface's log(String message) method by internally calling the old OldLogger.writeToLogFile(message), so new code can log through the modern interface while the legacy module keeps working unchanged.
Code Example:
interface Logger {
void log(String message);
}
class OldLogger {
void writeToLogFile(String entry) {
System.out.println("OLD LOG: " + entry);
}
}
class LegacyLoggerAdapter implements Logger {
private OldLogger oldLogger = new OldLogger();
public void log(String message) {
oldLogger.writeToLogFile(message);
}
}Interview Tip: A concise interview answer is:
"Say I'm integrating a legacy logging module that only exposes writeToLogFile() into an application that expects a modern Logger interface with a log() method. I write an adapter class that implements Logger and internally calls writeToLogFile(), so the rest of the app logs through the modern interface while the legacy module stays completely untouched."