🧩 OOP Concepts Intermediate

What is the Adapter pattern?

Answer

The Adapter pattern allows incompatible interfaces to work together. It acts as a bridge — wrapping an existing class with a new interface so it can work with code that expects a different interface. Like a power plug adapter that lets US plugs work in European outlets. Object adapter (composition): // Existing class we can't modify: class LegacyPaymentSystem { public void chargeCard(String cardNum, String expiry, int amountInCents) { System.out.println("Legacy charging: $" + amountInCents / 100.0); } } // New interface our system expects: interface ModernPaymentGateway { void processPayment(PaymentDetails details); } // Adapter bridges the gap: class LegacyPaymentAdapter implements ModernPaymentGateway { private LegacyPaymentSystem legacy; public LegacyPaymentAdapter(LegacyPaymentSystem legacy) { this.legacy = legacy; } @Override public void processPayment(PaymentDetails details) { // Translate ModernPaymentGateway call to LegacyPaymentSystem String cardNum = details.getCardNumber(); String expiry = details.getFormattedExpiry(); int cents = (int)(details.getAmount() * 100); legacy.chargeCard(cardNum, expiry, cents); } } // Our code only knows ModernPaymentGateway: LegacyPaymentSystem legacy = new LegacyPaymentSystem(); ModernPaymentGateway gateway = new LegacyPaymentAdapter(legacy); gateway.processPayment(paymentDetails); // Works with old system!. Class adapter (inheritance — Java with interfaces): adapter inherits from adaptee and implements target interface. Real examples: Arrays.asList() adapts array to List; InputStreamReader adapts byte stream to character stream; Java's Collections.enumeration() adapts Iterator to Enumeration; third-party library integrations. When to use: integrating legacy code with new interface requirements, using third-party libraries with incompatible interfaces, creating reusable components that work with classes that don't have the right interface.