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

Implementation

In the order you would write it, with the reason for every part.

The point: write the target first and the adapters last. If an adapter needs an if about the file type, you merged two adapters.

The media player, part by part

What the player wants, and the one error it must know.

from abc import ABC, abstractmethodclass PlaybackError(Exception):    """The only error our own code has to know."""class MediaPlayer(ABC):    @abstractmethod    def play(self, file_name, start_seconds=0): ...

Lines 4 to 5

Our own error. Without it the player would have to catch what each library throws, and with each library it would have to learn a new one.

1 of 3

Why it is built this way

  • Design it from the client's need, not from what the library offers.
  • A small target is easy to adapt. Each extra method must be possible in every library.