🔹 Adapter Pattern in Object-Oriented Programming (OOP)
The **Adapter Pattern** is a **structural design pattern** that allows two incompatible interfaces to work together. It acts as a bridge between **two different systems** by translating one interface into another.
📌 Why Use the Adapter Pattern?
The Adapter Pattern helps in integrating **legacy code, third-party libraries, or different APIs** with your existing system.
- ✅ **Bridges Incompatible Interfaces** – Allows different systems to communicate.
- ✅ **Reusability** – Use existing code without modifying it.
- ✅ **Flexibility** – Makes your code more adaptable to changes.
- ✅ **Follows Open-Closed Principle** – Extends functionality without modifying existing code.
💡 Real-Life Example
Imagine a **laptop charger adapter** that allows a **European plug** to fit into an **American socket**. The adapter converts the plug type but keeps the functionality the same.
🖥️ Adapter Pattern in Java
Example of an adapter converting **old payment system** to a **new payment gateway**.
interface NewPaymentGateway {
void processPayment(double amount);
}
// Old payment system (Incompatible)
class OldPaymentSystem {
void makePayment(double amount) {
System.out.println("Payment of $" + amount + " processed using old system.");
}
}
// Adapter to make old system work with new system
class PaymentAdapter implements NewPaymentGateway {
private OldPaymentSystem oldSystem;
PaymentAdapter(OldPaymentSystem oldSystem) {
this.oldSystem = oldSystem;
}
public void processPayment(double amount) {
oldSystem.makePayment(amount);
}
}
public class Main {
public static void main(String[] args) {
OldPaymentSystem oldSystem = new OldPaymentSystem();
NewPaymentGateway adapter = new PaymentAdapter(oldSystem);
adapter.processPayment(100.0);
}
}
🖥️ Adapter Pattern in Python
Example of an adapter converting **legacy text format** to **modern JSON format**.
class LegacyPrinter:
def print_text(self, text):
return f"Legacy Printer: {text}"
class JSONPrinterAdapter:
def __init__(self, legacy_printer):
self.legacy_printer = legacy_printer
def print_json(self, text):
return {"message": self.legacy_printer.print_text(text)}
# Using the adapter
legacy = LegacyPrinter()
adapter = JSONPrinterAdapter(legacy)
print(adapter.print_json("Hello, World!"))
🎯 Summary
The Adapter Pattern helps integrate **incompatible systems** by creating an **intermediate class (adapter)**. It is widely used in **payment gateways, third-party APIs, and legacy system integration**.