In this lesson, you will learn how to use the Adapter pattern to bridge the gap between incompatible interfaces by wrapping an existing component in a compatible structure.
The Problem of Interface Mismatch
Imagine you are building a system that expects every data source to have a fetch_data() method. However, you need to integrate a legacy module that provides information via a retrieve_info() method. You cannot change the legacy code, and you cannot rewrite your entire system to accommodate one specific class. This is where the Adapter pattern shines.
Creating the Adapter
The Adapter pattern works by creating a new class (the "wrapper") that implements the interface your system expects. Inside this wrapper, you hold a reference to the legacy component and delegate the calls to its specific methods.
Here is how you might connect a legacy service to a modern client:
# The interface our system expects
class DataReader:
def fetch_data(self):
pass
# The legacy component with a different interface
class LegacySystem:
def retrieve_info(self):
return {"id": 1, "status": "active"}
# The Adapter that makes LegacySystem compatible
class DataAdapter(DataReader):
def __init__(self, legacy_service):
self.legacy_service = legacy_service
def fetch_data(self):
# Translate the legacy method to our expected interface
return self.legacy_service.retrieve_info()
# Usage
legacy = LegacySystem()
adapter = DataAdapter(legacy)
print(adapter.fetch_data()) # System works as expected
Why this is effective
By using the Adapter pattern, you maintain composition over inheritance (concept 17). You aren't modifying the legacy class—you are simply creating a translation layer that adheres to the contract your system requires. This keeps your core application code decoupled from the idiosyncrasies of third-party libraries or older codebases.
The Adapter acts as a diplomat: it speaks the language of your system on one side and the language of the external component on the other, ensuring seamless integration without forcing structural changes on either party.
Key Takeaway: The Adapter pattern allows you to integrate legacy or third-party components by wrapping them in an object that translates their unique interface into the one your application requires.