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.

Easy Python 3.9+ Aug 9, 2026 Microservices patterns 13 views 0 copies

Python code

19 lines
Python 3.9+
class 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

stdout
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

  1. Use a class method `from_legacy` to create an adapter from a legacy instance
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Microservices patterns

Related tutorials and quizzes for this topic.