Adapter
Adapters allow two incompatible interfaces to work together by wrapping one around the other, thus acting as a bridge between disparate systems without modifying the code of either existing interface.
TL;DR
Used to wrap otherwise incompatible objects inside adapters to make it compatible with a different class.
Problem
Suppose you have an application that parses XML data from an API to monitor stock prices. However, you need to use a framework to analyse the data, but it only works with JSON. Rather than modify the framework itself (if that’s even possible) and potentially break internal logic, you can create an adapter
Solution
Adapters are special objects that convert the interface of one object so that another object can understand it. It is done in a way such that the conversion complexity is hidden, and the wrapped object isn’t even aware that the adapter exists. As an example, an adapter might convert metric measurements into imperial measurements.
The adapter can also be used to make incompatible systems play together.
Consider the example of an audio player. If we have a modern audio system that is incompatible with an old system, we can use the adaptor to add a compatibility layer:
# Example: Making incompatible audio players work together
# Third-party library with different interface
class OldAudioPlayer:
def play_old_format(self, filename):
return f"Playing {filename} using old audio system"
# Our application expects this interface
class ModernPlayer:
def play(self, filename):
return f"Playing {filename} using modern system"
# Adapter to make OldAudioPlayer compatible with our interface
class AudioAdapter:
def __init__(self, old_player):
self.old_player = old_player
def play(self, filename):
# Translate the interface
return self.old_player.play_old_format(filename)
# Client code that expects the modern interface
class MusicApp:
def __init__(self, player):
self.player = player
def start_music(self, song):
return self.player.play(song)
# Usage example
if __name__ == "__main__":
# Works with modern player
modern = ModernPlayer()
app1 = MusicApp(modern)
print(app1.start_music("song.mp3"))
# Works with old player through adapter
old = OldAudioPlayer()
adapted_old = AudioAdapter(old)
app2 = MusicApp(adapted_old)
print(app2.start_music("oldtrack.wav"))
# Output:
# Playing song.mp3 using modern system
# Playing oldtrack.wav using old audio system