Adapter Pattern
The Adapter pattern: wrapping an existing class so it fits the interface a client already expects, without changing either side.
Sometimes a class does exactly the job you need, and its interface is wrong: different method names, different arguments, money in pence where your code passes pounds. You cannot edit the class, because it belongs to a library or to code other systems depend on, and you should not rewrite your client around it. The Adapter pattern puts a small class between the two that translates each call.
This topic opens on that mismatch and the pattern's intent, then reads the three participants off the class diagram and compares the object adapter, which holds the class it adapts, with the class adapter, which inherits from it. The template shows the translation in Python, Java and TypeScript.
Two examples follow: a legacy payment gateway placed behind a checkout's interface, where the adapter converts units as well as names, and two adapters in Java's standard library, InputStreamReader and Arrays.asList. The gotcha is an adapter that starts doing the work it was only meant to pass on, and the exercise adapts a Celsius sensor to a dashboard that reads Fahrenheit.
By the end you can recognise an adapter, and name its target, adapter and adaptee in real code.
Contents
8 cardsnot started