Java Adapter Pattern: Class vs Object Adapters with Code Examples
This article explains the Java Adapter design pattern, covering its definition, roles (Target, Adapter, Adaptee), and two implementation approaches—class adapter using inheritance and object adapter using composition—with complete code examples for each.
Java Adapter Pattern Overview
The Adapter pattern is a structural design pattern that converts the interface of a class into another interface that clients expect. It enables incompatible interfaces to work together.
Key Roles
Target : The interface the client expects.
Adapter : Implements the Target interface and holds a reference to the Adaptee.
Adaptee : The existing interface that needs adaptation.
Common Use Cases
Refactoring legacy code: converting old interfaces to new ones.
System integration: bridging interfaces between two systems.
Adopting new interfaces: making a new incompatible interface work with existing code.
Implementation Approaches
1. Class Adapter (Inheritance)
The adapter extends the Adaptee and implements the Target interface.
public interface Target {
void request();
}
public interface Adaptee {
void specificRequest();
}
public class Adapter extends Adaptee implements Target {
@Override
public void request() {
specificRequest();
}
}2. Object Adapter (Composition)
The adapter implements the Target interface and contains an instance of Adaptee.
public interface Target {
void request();
}
public interface Adaptee {
void specificRequest();
}
public class AdapteeImpl implements Adaptee {
@Override
public void specificRequest() {
// concrete implementation
}
}
public class Adapter implements Target {
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
@Override
public void request() {
adaptee.specificRequest();
}
}The class adapter uses inheritance, while the object adapter uses composition, offering more flexibility.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Architect Chen
Sharing over a decade of architecture experience from Baidu, Alibaba, and Tencent.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
