2.1 Adapter
The Adapter pattern solves a very concrete real-world problem: two pieces of code should cooperate, but their interfaces don't line up. You have a ready-made class (or third-party library, or legacy system) whose functionality is exactly right, but its method names, parameters, and return values don't match the interface your client expects. The adapter "translates" in between so neither side has to change.
The simplest analogy is a travel power adapter: the laptop plug does not change, the wall socket does not change, and the adapter handles the shape in between. In real systems, it may also have to handle constraints such as voltage, units, or argument shape.
Object adapter vs class adapter
Adapters come in two flavors:
- Object adapter (preferred): the adapter composes an adaptee object and forwards requests to it. Flexible, free of inheritance limits, and able to adapt a whole family of subclasses.
- Class adapter: the adapter inherits both the target interface and the adaptee class (requires multiple inheritance; in Java you can only extend one class).
// Object adapter: composition
class MediaAdapter implements MediaPlayer {
private AdvancedPlayer advanced; // holds the adaptee
public void play(String type, String file) {
if (type.equals("mp4")) advanced.playMp4(file); // translate
else if (type.equals("vlc")) advanced.playVlc(file);
}
}The player adapter lab below works like a wiring test: the app has one play(file) button, while the old player only has legacy buttons such as playMp3(), playMp4(), and playVlc(). Plug in the adapter and it presses the right old button for the app.
An adapter is not an excuse
An adapter is a compatibility layer; its value is isolating incompatibility. But beware:
- If you can change the adaptee directly and it really is poorly designed, you should fix it rather than permanently smear an adapter over it.
- Keep the adapter to interface translation only — no business logic. The moment an adapter starts doing computation, validation, or state management, it has mutated into a quietly growing middle layer.