Design Patterns - Adapter

Design Patterns - Adapter

The Adapter design pattern is a structural design pattern that allows objects with incompatible interfaces to work together. It acts as a bridge between two incompatible interfaces, converting the interface of one class into another interface that clients expect. This pattern enables classes to collaborate that otherwise wouldn't be able to due to their incompatible interfaces. Let's say we have an existing client code that expects a certain interface to interact with a target class. However, we want to use a different class that has a different interface. Instead of modifying the client code or the existing class, we can introduce an adapter class that implements the expected interface and internally delegates the calls to the different class.

The components of the Adapter pattern are:

Target: This is the interface that the client code expects to interact with. It defines the operations that the client can use.

Adaptee: This is the existing class or component that has an incompatible interface with the client code.

Adapter: This is the class that implements the Target interface and internally uses the Adaptee. It acts as a wrapper that translates the client's requests into the appropriate calls to the Adaptee.

Example of the Adapter design pattern implemented in Python

# Target interface
class MediaPlayer:
    def play(self, audio_type, filename):
        pass

# Adaptee class
class AdvancedMediaPlayer:
    def play_vlc(self, filename):
        print("Playing VLC file:", filename)

    def play_mp4(self, filename):
        print("Playing MP4 file:", filename)

# Adapter class
class MediaAdapter(MediaPlayer):
    def __init__(self, audio_type):
        self.advanced_player = AdvancedMediaPlayer()
        self.audio_type = audio_type

    def play(self, audio_type, filename):
        if audio_type == "vlc" and self.audio_type == "vlc":
            self.advanced_player.play_vlc(filename)
        elif audio_type == "mp4" and self.audio_type == "mp4":
            self.advanced_player.play_mp4(filename)

# Client code
class AudioPlayer:
    def play(self, audio_type, filename):
        if audio_type == "mp3":
            print("Playing MP3 file:", filename)
        elif audio_type == "vlc" or audio_type == "mp4":
            media_adapter = MediaAdapter(audio_type)
            media_adapter.play(audio_type, filename)
        else:
            print("Invalid media type:", audio_type)

# Usage
audio_player = AudioPlayer()
audio_player.play("mp3", "song.mp3")
audio_player.play("vlc", "movie.vlc")
audio_player.play("mp4", "video.mp4")
audio_player.play("avi", "video.avi")

Popular posts from this blog

Atom - Jupyter / Hydrogen

Design Patterns

Robson Koji Moriya disambiguation name