When should you use the Adapter pattern in a project?
The Adapter pattern should be used when you need to connect incompatible interfaces: that is, to make classes or modules that were not originally designed to work together do so.
1. Integrating Legacy Code with a New System
When you are modernizing a system but cannot change the legacy components. The adapter "translates" the old interface into the new one, preserving functionality without rewriting the logic.
Example:
The new system uses PaymentService.process(), while the old module uses LegacyPay.runPayment().
The adapter implements PaymentService, internally calling LegacyPay.runPayment().
2. Using Third-Party Libraries and APIs
If an external SDK, library, or API has a different interface, an adapter lets you integrate it without changing either the library or your code.
Example:
You use an external email service whose methods are named differently - the adapter fits it to your internal EmailSender interface.
3. Aligning Interfaces of Different Classes
When you have several similar classes with different interfaces that need to be used in a uniform way. The adapter creates a single interaction contract.
Example:
The classes XmlDataReader and JsonDataReader are brought to a common DataReader interface through adapters.
4. Working with Legacy Systems
Enterprise projects often keep old modules that are expensive or impossible to change. The adapter lets you temporarily "cover" the old code with a new interface, preserving backward compatibility.
5. Gradual Transition Between Architectures
During migration from a monolith to microservices, an API change, or a move to new data formats (XML to JSON). The adapter acts as a temporary bridge until the systems are unified.
6. Conclusion
Use Adapter when:
- classes cannot be changed but need to be combined;
- interfaces differ, but the logic must be shared;
- you need to preserve legacy code or external dependencies without breaking the architecture.
Summary: Adapter is applied when you need to ensure compatibility without modifying the original code, acting as a "translator" between two worlds.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.