Junior — Middle
Can you explain how the Adapter design pattern works and its purpose?
sobes.tech AI
Answer from AI
The Adapter design pattern is used to make the interface of one class compatible with the interface expected by the client. This allows classes with incompatible interfaces to work together.
The Adapter acts as a "translator" between two objects.
Example in Java:
// Target interface expected by the client
interface Target {
void request();
}
// Class with incompatible interface
class Adaptee {
void specificRequest() {
System.out.println("Specific request");
}
}
// Adapter implementing Target and calling Adaptee
class Adapter implements Target {
private Adaptee adaptee;
Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
public void request() {
adaptee.specificRequest();
}
}
// Usage
public class Client {
public static void main(String[] args) {
Adaptee adaptee = new Adaptee();
Target target = new Adapter(adaptee);
target.request(); // calls the specific request through the adapter
}
}
Thus, the Adapter allows existing classes to be integrated without modifying their code.