Overview
The Adapter Design Pattern acts as a bridge between two incompatible interfaces. It allows classes with incompatible interfaces to work together by wrapping an existing class with a new interface.
Key Characteristics
- Converts the interface of a class into another interface the client expects.
- Allows existing classes to work together without modifying their source code.
- Promotes reusability and flexibility in code.
Implementation
The following is an example of an Adapter implementation in Java:
interface Target {
void request();
}
class Adaptee {
public void specificRequest() {
System.out.println("Specific request called.");
}
}
class Adapter implements Target {
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
@Override
public void request() {
adaptee.specificRequest();
}
}
public class AdapterDemo {
public static void main(String[] args) {
Adaptee adaptee = new Adaptee();
Target target = new Adapter(adaptee);
target.request();
}
}
When to Use
- When you need to use an existing class but its interface does not match the one you need.
- When you want to create reusable code that works with unrelated or legacy classes.
Advantages
- Promotes reusability of existing classes without modifying their source code.
- Decouples the client code from the implementation details of the adaptee.
Disadvantages
- Can add complexity to the codebase due to additional layers of abstraction.