🚀 Enjoying Java Tutorials?
Subscribe to Ram N Java for clean, beginner-friendly core Java tutorials and interview prep!
🔔 Subscribe to Ram N JavaIntroduction
The Adapter Design Pattern is a structural design pattern that bridges two incompatible interfaces, allowing them to collaborate seamlessly. To understand how the pattern is modeled in software architecture, we look at its UML Class Diagrams. Depending on whether you use object composition or class inheritance, the pattern takes the form of an Object Adapter or a Class Adapter.
Key Participants in the Class Diagram
- Client: The class containing the business logic that invokes operations through the Target interface.
- Target Interface: Defines the domain-specific contract or method signatures that the Client expects to interact with (e.g.,
request()). - Adaptee: The existing class or legacy/third-party component that contains useful functionality but provides an incompatible interface (e.g.,
specificRequest()). - Adapter: The intermediary class that implements the Target interface and maps calls from the Client to the Adaptee.
Object Adapter vs. Class Adapter Diagram
1. Object Adapter (Composition)
In the Object Adapter design:
- The
Adapterclass implements theTargetinterface. - The
Adaptermaintains an instance variable reference to theAdaptee(has-a relationship / composition). - When
request()is called, the Adapter delegates the call toadaptee.specificRequest().
2. Class Adapter (Inheritance)
In the Class Adapter design:
- The
Adapterclass implements theTargetinterface. - The
Adapterdirectly extends (subclasses) theAdapteeclass (is-a relationship / inheritance). - When
request()is called, the Adapter calls the inherited methodspecificRequest()directly.
Structural Comparison
| Feature | Object Adapter | Class Adapter |
|---|---|---|
| Relationship with Adaptee | Composition (Holds a reference) | Inheritance (Extends Adaptee) |
| Flexibility | High (Works with Adaptee and all its subclasses) | Rigid (Tied to a specific Adaptee class) |
| Java Support | Fully supported and preferred | Requires Target to be an interface due to single inheritance |
Related Tutorials from Ram N Java
Click here to watch in Youtube : https://www.youtube.com/watch?v=AFNWK3Wo1DA
Click the below Image to Enlarge
See also: