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
Requirements
What to ask, and the promises of the target interface.
The point: the target interface is a list of promises. Find them before you look at the libraries, or the libraries will write them for you.
Ask
Questions that change the design
| Question | Answer here | What it decides |
|---|---|---|
| Can the libraries be changed? | No | Adapter, not rename |
| Which unit does the user see? | Seconds | The target uses seconds |
| Start in the middle? | Yes, resume | A second parameter |
| What if a file is broken? | Show one message | One error type of ours |
| Two songs at once? | No | One decoder per player is enough |
| Can one library be replaced later? | Likely | No type of the library may leave the adapter |
Promises
The contract of MediaPlayer
- 1
Same input, same meaning
start_secondsis in seconds from the beginning, for every format. - 2
All or nothing
Either the file plays, or
PlaybackError. Never an old file, never silence. - 3
One error family
No number, no exception of a library passes the border.
- 4
No leftovers
A call does not depend on the call before it.
Gap list
Compare the promises with each library
| Promise | VlcEngine | Mp4Decoder |
|---|---|---|
| Name | play_vlc | load, seek, run |
| Unit | milliseconds | milliseconds |
| Error | none that we know of | return code of load |
| State | none | keeps the loaded file |
| Adapter must | rename, times 1000 | order the calls, check the code, times 1000 |