What is the Adapter pattern and when would you use it?

The Adapter pattern is a structural pattern that lets objects with incompatible interfaces work together by converting one class's interface into another interface the client expects. It's used to integrate code you can't or don't want to modify with code that expects a different contract.

Key Points: • The adapter implements the target interface the client already depends on. • Internally, the adapter holds a reference to the incompatible (adaptee) class and translates calls to it. • It's the standard tool for integrating third-party libraries or legacy code without rewriting either side. • Unlike Facade, which simplifies a subsystem, Adapter's specific job is making one interface conform to another. • Object adapters use composition (holding a reference to the adaptee) and are generally preferred in Java over class adapters that would require multiple inheritance.

Example: Wrapping a legacy XmlLogger behind a Logger interface used by the rest of the application lets new code call logger.log(message) while the adapter internally calls xmlLogger.writeXmlEntry(message).

Code Example:

interface Logger {
    void log(String message);
}

class LegacyXmlLogger {
    void writeXmlEntry(String msg) { System.out.println("<log>" + msg + "</log>"); }
}

class XmlLoggerAdapter implements Logger {
    private LegacyXmlLogger legacyLogger;
    XmlLoggerAdapter(LegacyXmlLogger legacyLogger) { this.legacyLogger = legacyLogger; }
    public void log(String message) { legacyLogger.writeXmlEntry(message); }
}

Interview Tip: A concise interview answer is:

"Adapter converts one interface into another that the client already expects, which is exactly what I need when integrating a third-party library or legacy code without rewriting either side. I write a class that implements the interface my code expects and internally delegates to the incompatible class, translating calls between the two."