Skip to content

Instantly share code, notes, and snippets.

@aoloe aoloe/README.md
Last active Jul 10, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.