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
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
Interviewer
Our audio player plays MP3. We bought two libraries, one for VLC files and one for MP4. Add both.
You
May I change the libraries, and do I expect more formats?
Interviewer
You can not change them, they arrive as binaries. More formats will come.
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.Interviewer
Is one adapter with an if not enough?
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
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 NoneWhat the first try costs
| Change | Classes to edit | Risk |
|---|---|---|
| A third library | MediaAdapter | The if chain grows, all formats are tested again |
play("mp4", "song.vlc") | none, it just happens | Wrong library for the file |
| The MP4 library returns 415 | none | The previous file is played again |
| Test the VLC part alone | none | You must build an MP4 decoder too |
How the wrong film starts
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
ifhas become data.