Class vs Object Adapters
What you'll learn: You'll discover the two ways to implement the Adapter pattern—one using inheritance, the other using composition—and when to choose each approach.
The Core Difference
Remember the Adapter pattern lets you make incompatible interfaces work together. But how you build that adapter matters. There are two fundamental approaches:
- Class Adapter – uses inheritance to adapt one interface to another
- Object Adapter – uses composition to wrap and delegate to the adaptee
Class Adapter: The Inheritance Approach
A class adapter inherits from the existing class (the "adaptee") and implements the target interface. It directly extends the adaptee's behavior, gaining access to all its methods (including protected ones). Think of it like being bilingual from birth—you inherit both languages naturally.
Limitation: Many languages (like Java) don't support multiple inheritance, so if you need to implement an interface and extend a class simultaneously, you may face constraints. Also, you're tightly coupled to the specific adaptee class—you can't adapt similar classes without creating new adapter subclasses.
Object Adapter: The Composition Approach
An object adapter holds a reference to the adaptee and delegates calls to it. It implements the target interface but uses composition to forward requests. This is like being a translator—you don't need to be both parties, you just facilitate communication between them.
Advantage: You can adapt any class that shares the same interface (or even multiple different classes). It's more flexible and honors the principle "favor composition over inheritance" you learned earlier. You're loosely coupled to the adaptee.
Trade-off: You can't access protected members of the adaptee, only public ones.
Which Should You Choose?
Use object adapters by default—they're more flexible and reusable. Use class adapters only when you specifically need access to protected methods or when your language makes it convenient.
Key Takeaway: Class adapters use inheritance and tightly couple to one adaptee; object adapters use composition and provide greater flexibility for adapting multiple or changing adaptees.