How to Use the Adapter Pattern to Mock a Legacy System in Python
This code demonstrates the Adapter pattern, allowing a modern interface to interact with a legacy system by wrapping its outdated method.
Python code
19 linesclass LegacySystem:
def legacy_method(self, data):
return f"Legacy processed: {data}"
class ModernInterface:
def process(self, data):
raise NotImplementedError
class Adapter(ModernInterface):
def __init__(self, legacy):
self.legacy = legacy
def process(self, data):
return self.legacy.legacy_method(data)
if __name__ == "__main__":
legacy = LegacySystem()
adapter = Adapter(legacy)
print(adapter.process("test data"))
Output
Legacy processed: test data
How it works
The Adapter pattern bridges incompatible interfaces by creating a wrapper that translates modern calls to legacy implementations. Here, ModernInterface defines a common contract, while Adapter implements it using the LegacySystem's legacy_method. The adapter is instantiated with the legacy object and exposes a clean process method to clients, hiding the legacy complexity. This promotes loose coupling and allows swapping legacy systems without changing client code.
Common mistakes
- Forgetting to call super().__init__() when subclassing if needed
- Hardcoding the legacy instance instead of injecting it via __init__
- Not raising NotImplementedError in the interface to enforce contracts
Variations
- Use a class method `from_legacy` to create an adapter from a legacy instance
- Implement the adapter as a function with a closure capturing the legacy object
Real-world use cases
- Integrating an old payment gateway into a modern checkout service without refactoring the gateway.
- Wrapping a legacy CRM API for a new microservice that expects a unified data interface.
- Mocking a legacy mainframe system in unit tests to simulate responses in a controlled environment.
Sponsored
More from Microservices patterns
- BFF aggregation pattern: combine multiple service responses in Python easy
- Backward Compatible Schema Evolution in Python medium
- Bulkhead Thread Pool per Service Mock in Python medium
- CQRS with Separate Read and Write Repositories in Python medium
- Cache-Aside Pattern in Python: Per-Service Mock easy
- Consumer Driven Contract Pact Mock in Python medium
Keep learning
Related tutorials and quizzes for this topic.