Java › Design Patterns in Java
What is the Adapter pattern, and when would you use it to make an existing class compatible with an interface it wasn't originally designed to implement?
IntermediateAnswer
Adapter wraps an existing class (with an incompatible interface) inside a new class that implements the interface your code actually needs, translating calls between the two -- commonly used when integrating a third-party library or legacy class whose API doesn't match what your code expects, letting you avoid modifying the original class (which you may not even have access to modify) while still making it usable wherever the target interface is expected.
// Third-party class with an incompatible interface you can't modify
class LegacyRectangle {
void oldDraw(int x1, int y1, int x2, int y2) { /* ... */ }
}
// Your application's expected interface
interface Shape { void draw(); }
// Adapter bridges the two
class RectangleAdapter implements Shape {
private final LegacyRectangle legacy;
private final int x, y, width, height;
public RectangleAdapter(LegacyRectangle legacy, int x, int y, int w, int h) {
this.legacy = legacy; this.x = x; this.y = y; this.width = w; this.height = h;
}
public void draw() { legacy.oldDraw(x, y, x + width, y + height); }
}Real-world example A modern application integrating a legacy third-party billing library (with an API predating the application's own PaymentProcessor interface) wraps the legacy library's class in an Adapter implementing PaymentProcessor, letting the rest of the codebase interact with it through the consistent modern interface without any changes to the legacy library itself.