Python Adapter Class: Wrap Legacy Interface
Convert a legacy system's interface into a modern one using the Adapter pattern in Python, translating method calls and data formats.
Python code
29 linesclass LegacySystem:
"""Legacy interface - old method names and parameter format."""
def query_employee_info(self, emp_id, emp_name):
return f"Legacy: {emp_id} - {emp_name}"
def update_employee_department(self, emp_id, department_code):
return f"Legacy: Updated {emp_id} to dept {department_code}"
class EmployeeAdapter:
"""Adapter to expose a modern interface over LegacySystem."""
def __init__(self, legacy_system):
self._legacy = legacy_system
def get_employee(self, employee_id):
# New interface takes just ID; adapter provides a default name
return self._legacy.query_employee_info(employee_id, "Unknown")
def set_employee_department(self, employee_id, department_name):
# Map friendly department name to legacy numeric code
dept_codes = {"Engineering": 101, "Sales": 202, "HR": 303}
code = dept_codes.get(department_name, 000)
return self._legacy.update_employee_department(employee_id, code)
if __name__ == "__main__":
legacy = LegacySystem()
adapter = EmployeeAdapter(legacy)
print(adapter.get_employee(12345))
print(adapter.set_employee_department(12345, "Engineering"))
Output
Legacy: 12345 - Unknown
Legacy: Updated 12345 to dept 101
How it works
The EmployeeAdapter class wraps a LegacySystem instance and exposes a new interface with get_employee and set_employee_department. It translates the modern method calls into the legacy methods, providing default parameters and mapping domain names to codes. This enables existing code to use the legacy system without modification.
Common mistakes
- Forgetting to pass the legacy system to the adapter constructor
- Hardcoding department mappings outside the adapter, breaking encapsulation
Variations
- Use `__getattr__` to dynamically delegate unknown methods to the legacy object
Real-world use cases
- Integrating with an old enterprise HR system from a new microservice without changing the legacy code
- Wrapping a third-party SDK with a cleaner API for internal team use
- Adapting a legacy payment gateway to a unified payment interface across multiple providers
Sponsored
More from OOP & classes
- Add property getter setter validation in Python easy
- Binary Tree Inorder Traversal in Python easy
- Borg pattern shared state in Python medium
- Bridge Pattern in Python: Separate Abstraction from Implementation medium
- Composable Predicates with the &, |, ~ Operators in Python medium
- Composition over Inheritance: How to Build a Wallet Account in Python easy
Keep learning
Related tutorials and quizzes for this topic.