Adapter pattern
easy 50 minThe 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)
| Step | Object | Call | State afterwards |
|---|---|---|---|
| 1 | AudioPlayer | extension is mp4 | found Mp4Adapter |
| 2 | Mp4Adapter | load("video.mp4") | path set, position 0, code 0 |
| 3 | Mp4Adapter | seek(5000) | position 5000 |
| 4 | Mp4Adapter | run() | mp4:video.mp4@5000ms |
| 5 | AudioPlayer | returns it | unchanged |
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")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);}Extend
Add a third library and count
| New requirement | New | Changed |
|---|---|---|
| OGG through another library | OggAdapter | One line of wiring |
| The MP4 library is replaced | FastMp4Adapter | One line of wiring |
| Volume for all formats | nothing | The target and every player |
| Show the film's length | nothing | The target, and each library must be able to tell |