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

Problem

One player, three formats, two foreign libraries.

The point: the player is not hard because of sound. It is hard because each library has its own words, its own order and its own way to say no.

The task

What we are asked

The first two minutes

  1. Interviewer

    Our audio player plays MP3. We bought two libraries, one for VLC files and one for MP4. Add both.

  2. You

    May I change the libraries, and do I expect more formats?

  3. Interviewer

    You can not change them, they arrive as binaries. More formats will come.

  4. You

    Then I would not let the player learn each library. I write the interface that the player wants, one play(file, start), and one adapter per library. A new format is then one class and one line of wiring.

  5. Interviewer

    Is one adapter with an if not enough?

  6. You

    With two formats it would work. But then each new format edits a class that already works, and one library with an error code makes the code of the other harder to read. Let me show it.

First try

One adapter for everything

Python
class MediaAdapter:    def __init__(self, vlc, mp4):        self._vlc = vlc        self._mp4 = mp4    def play(self, kind, file_name, start_seconds=0):        if kind.lower() == "vlc":            return self._vlc.play_vlc(file_name, start_seconds * 1000)        elif kind.lower() == "mp4":            self._mp4.load(file_name)           # the code is ignored            self._mp4.seek(start_seconds * 1000)            return self._mp4.run()        else:            print("Unsupported format:", kind)  # and returns None
Three problems: the type is passed beside the file and can disagree with it, the error code is lost, and an unknown format prints something and returns None.

What the first try costs

ChangeClasses to editRisk
A third libraryMediaAdapterThe if chain grows, all formats are tested again
play("mp4", "song.vlc")none, it just happensWrong library for the file
The MP4 library returns 415noneThe previous file is played again
Test the VLC part alonenoneYou must build an MP4 decoder too

How the wrong film starts

Nobody wrote a wrong line. Somebody did not read an answer.

How should the player find the right library?

BreaksThe caller passes the type
How
play("vlc", file)
Limit
Two facts about one file, and they can contradict each other.
Choose when
Never, if the file name already says it.
WorksAn if chain on the extension in the player
How
The player knows all formats.
Limit
Every new format edits the player.
Choose when
Two formats that will stay two.
StrongA map from extension to MediaPlayer
How
The program fills the map when it starts. The player looks up and calls.
Limit
Somebody must fill the map, in one place.
Choose when
When formats are added. The if has become data.