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

Media player with two adapters

Read it, run it, change a line and run it again.

Loading editor…

Complete and runnable. Try it: add an OGG library whose call is `open_stream(name, start_frame)` with 50 frames a second.

The same in Java
import java.util.Map;class PlaybackError extends RuntimeException {    PlaybackError(String message) { super(message); }}interface MediaPlayer {    String play(String fileName, int startSeconds);}final class VlcEngine {                 // library one    String playVlc(String path, int offsetMs) {        return "vlc:" + path + "@" + offsetMs + "ms";    }}final class Mp4Decoder {                // library two    private String path;    private int position;    int load(String path) {        if (!path.endsWith(".mp4")) return 415;        this.path = path;        this.position = 0;        return 0;    }    void seek(int ms) { position = ms; }    String run() { return "mp4:" + path + "@" + position + "ms"; }}final class VlcAdapter implements MediaPlayer {    private final VlcEngine engine;    VlcAdapter(VlcEngine engine) { this.engine = engine; }    @Override    public String play(String fileName, int startSeconds) {        return engine.playVlc(fileName, startSeconds * 1000);    }}final class Mp4Adapter implements MediaPlayer {    private final Mp4Decoder decoder;    Mp4Adapter(Mp4Decoder decoder) { this.decoder = decoder; }    @Override    public String play(String fileName, int startSeconds) {        int code = decoder.load(fileName);        if (code != 0) throw new PlaybackError("can not play " + fileName);        decoder.seek(startSeconds * 1000);        return decoder.run();    }}final class Mp3Player implements MediaPlayer {    @Override    public String play(String fileName, int startSeconds) {        return "mp3:" + fileName + "@" + startSeconds * 1000 + "ms";    }}final class AudioPlayer {    private final Map<String, MediaPlayer> players;    AudioPlayer(Map<String, MediaPlayer> players) { this.players = players; }    String open(String fileName, int startSeconds) {        String extension = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();        MediaPlayer player = players.get(extension);        if (player == null) throw new PlaybackError("no player for " + extension);        return player.play(fileName, startSeconds);    }}class Main {    public static void main(String[] args) {        AudioPlayer app = new AudioPlayer(Map.of(            "mp3", new Mp3Player(),            "vlc", new VlcAdapter(new VlcEngine()),            "mp4", new Mp4Adapter(new Mp4Decoder())));        System.out.println(app.open("song.mp3", 0));    // mp3:song.mp3@0ms        System.out.println(app.open("movie.vlc", 90));  // vlc:movie.vlc@90000ms        System.out.println(app.open("video.mp4", 5));   // mp4:video.mp4@5000ms    }}
The same in C++
#include <iostream>#include <map>#include <memory>#include <stdexcept>#include <string>#include <utility>struct PlaybackError : std::runtime_error {    using std::runtime_error::runtime_error;};class MediaPlayer {public:    virtual ~MediaPlayer() = default;    virtual std::string play(const std::string& file, int startSeconds) = 0;};class VlcEngine {                       // library onepublic:    std::string playVlc(const std::string& path, int offsetMs) {        return "vlc:" + path + "@" + std::to_string(offsetMs) + "ms";    }};class Mp4Decoder {                      // library two    std::string path;    int position = 0;public:    int load(const std::string& p) {        if (!p.ends_with(".mp4")) return 415;        path = p;        position = 0;        return 0;    }    void seek(int ms) { position = ms; }    std::string run() { return "mp4:" + path + "@" + std::to_string(position) + "ms"; }};class VlcAdapter : public MediaPlayer {    VlcEngine engine;public:    explicit VlcAdapter(VlcEngine e) : engine(std::move(e)) {}    std::string play(const std::string& file, int startSeconds) override {        return engine.playVlc(file, startSeconds * 1000);    }};class Mp4Adapter : public MediaPlayer {    Mp4Decoder decoder;public:    explicit Mp4Adapter(Mp4Decoder d) : decoder(std::move(d)) {}    std::string play(const std::string& file, int startSeconds) override {        if (decoder.load(file) != 0) throw PlaybackError("can not play " + file);        decoder.seek(startSeconds * 1000);        return decoder.run();    }};class Mp3Player : public MediaPlayer {public:    std::string play(const std::string& file, int startSeconds) override {        return "mp3:" + file + "@" + std::to_string(startSeconds * 1000) + "ms";    }};class AudioPlayer {    std::map<std::string, std::unique_ptr<MediaPlayer>> players;public:    void add(const std::string& extension, std::unique_ptr<MediaPlayer> player) {        players[extension] = std::move(player);    }    std::string open(const std::string& file, int startSeconds = 0) {        std::string extension = file.substr(file.rfind('.') + 1);        auto found = players.find(extension);        if (found == players.end()) throw PlaybackError("no player for " + extension);        return found->second->play(file, startSeconds);    }};int main() {    AudioPlayer app;    app.add("mp3", std::make_unique<Mp3Player>());    app.add("vlc", std::make_unique<VlcAdapter>(VlcEngine{}));    app.add("mp4", std::make_unique<Mp4Adapter>(Mp4Decoder{}));    std::cout << app.open("song.mp3") << "\n"              << app.open("movie.vlc", 90) << "\n"              << app.open("video.mp4", 5) << "\n";}
The same in TypeScript
class PlaybackError extends Error {}interface MediaPlayer {  play(fileName: string, startSeconds?: number): string;}class VlcEngine { // library one  playVlc(path: string, offsetMs: number): string {    return `vlc:${path}@${offsetMs}ms`;  }}class Mp4Decoder { // library two  private path = "";  private position = 0;  load(path: string): number {    if (!path.endsWith(".mp4")) return 415;    this.path = path;    this.position = 0;    return 0;  }  seek(ms: number): void { this.position = ms; }  run(): string { return `mp4:${this.path}@${this.position}ms`; }}class VlcAdapter implements MediaPlayer {  constructor(private readonly engine: VlcEngine) {}  play(fileName: string, startSeconds = 0): string {    return this.engine.playVlc(fileName, startSeconds * 1000);  }}class Mp4Adapter implements MediaPlayer {  constructor(private readonly decoder: Mp4Decoder) {}  play(fileName: string, startSeconds = 0): string {    const code = this.decoder.load(fileName);    if (code !== 0) throw new PlaybackError(`can not play ${fileName}`);    this.decoder.seek(startSeconds * 1000);    return this.decoder.run();  }}class Mp3Player implements MediaPlayer {  play(fileName: string, startSeconds = 0): string {    return `mp3:${fileName}@${startSeconds * 1000}ms`;  }}class AudioPlayer {  constructor(private readonly players: Map<string, MediaPlayer>) {}  open(fileName: string, startSeconds = 0): string {    const extension = fileName.slice(fileName.lastIndexOf(".") + 1).toLowerCase();    const player = this.players.get(extension);    if (!player) throw new PlaybackError(`no player for ${extension}`);    return player.play(fileName, startSeconds);  }}const app = new AudioPlayer(new Map<string, MediaPlayer>([  ["mp3", new Mp3Player()],  ["vlc", new VlcAdapter(new VlcEngine())],  ["mp4", new Mp4Adapter(new Mp4Decoder())],]));console.log(app.open("song.mp3")); // mp3:song.mp3@0msconsole.log(app.open("movie.vlc", 90)); // vlc:movie.vlc@90000msconsole.log(app.open("video.mp4", 5)); // mp4:video.mp4@5000ms