AlgoViz

Adapter pattern

easy 50 min

The Adapter pattern makes an existing class fit the interface that its client expects, without changing either of them.

Watch lesson4:39

Verify

Trace by hand, test with a fake, then extend.

The point: a test of an adapter asks two things. Did the right words reach the adaptee, and did the right answer come back?

By hand

Trace open("video.mp4", 5)

StepObjectCallState afterwards
1AudioPlayerextension is mp4found Mp4Adapter
2Mp4Adapterload("video.mp4")path set, position 0, code 0
3Mp4Adapterseek(5000)position 5000
4Mp4Adapterrun()mp4:video.mp4@5000ms
5AudioPlayerreturns itunchanged

By machine

A fake that writes down what it hears

Python
class PlaybackError(Exception):    passclass Mp4Adapter:    def __init__(self, decoder):        self._decoder = decoder    def play(self, file_name, start_seconds=0):        if self._decoder.load(file_name) != 0:            raise PlaybackError(f"can not play {file_name}")        self._decoder.seek(start_seconds * 1000)        return self._decoder.run()class FakeDecoder:    def __init__(self, code=0):        self.code, self.calls = code, []    def load(self, path):        self.calls.append(("load", path))        return self.code    def seek(self, ms):        self.calls.append(("seek", ms))    def run(self):        self.calls.append(("run",))        return "frames"ok = FakeDecoder()assert Mp4Adapter(ok).play("a.mp4", 5) == "frames"assert ok.calls == [("load", "a.mp4"), ("seek", 5000), ("run",)]     # names, order, unitbad = FakeDecoder(code=415)try:    Mp4Adapter(bad).play("a.mov")    raise AssertionError("no error raised")except PlaybackError:    passassert ("run",) not in bad.calls                                     # nothing playedprint("translation and refusal are right")
The fake replaces the library, so the test needs no film and no decoder. The last assertion is the bug from the first page.
Edit and run it in your browser
Java
@Testvoid translatesSecondsToMilliseconds() {    VlcEngine engine = mock(VlcEngine.class);   // final classes need Mockito's inline mock maker    new VlcAdapter(engine).play("movie.vlc", 90);    verify(engine).playVlc("movie.vlc", 90_000);}
The same idea with JUnit and Mockito. Verify the value, not only that some call happened.

Extend

Add a third library and count

New requirementNewChanged
OGG through another libraryOggAdapterOne line of wiring
The MP4 library is replacedFastMp4AdapterOne line of wiring
Volume for all formatsnothingThe target and every player
Show the film's lengthnothingThe target, and each library must be able to tell
Adding an adaptee is cheap. Adding a promise is expensive. Say both when they ask whether the design is open for extension.