Skip to content

Instantly share code, notes, and snippets.

@aoloe
Last active July 10, 2018 09:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aoloe/f5233cfe9c43d6ecdb0f47968dc6725a to your computer and use it in GitHub Desktop.
Save aoloe/f5233cfe9c43d6ecdb0f47968dc6725a to your computer and use it in GitHub Desktop.
Python classes for exercising the adapter pattern

Adapter pattern with Python: the music player

Without modifying:

  • the Media_player_audio and Media_player_video interfaces
  • nor the Media_player_mp4 class

add an adapter that allows the music player to play the sound of an mp4 file.

import os
class Music_player:
def load_engines(self):
self.engines = {'.mp3': Media_player_mp3(), '.wav': Media_player_wav()}
def play(self, filename):
_, extension = os.path.splitext(filename)
self.engines[extension].play(filename)
class Media_player_audio:
def play(self, file_name, audio_format):
print("music from {} as {}".format(file_name, audio_format))
class Media_player_mp3(Media_player_audio):
def play(self, file_name):
super().play(file_name, "mp3")
class Media_player_wav(Media_player_audio):
def play(self, file_name):
super().play(file_name, "wav")
class Media_player_video:
def play(self, file_name, video_format):
print("video from {} as {}".format(file_name, video_format))
def play_audio(self, file_name, audio_format):
print("music from {} as {}".format(file_name, audio_format))
class Media_player_mp4(Media_player_video):
def play_audio(self, file_name):
super().play_audio(file_name, "mp4")
def main():
mp = Music_player()
mp.load_engines()
mp.play('baubau.mp3')
mp.play('baubau.wav')
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment