Junior
What is an adapter in the context of Java programming?
sobes.tech AI
Answer from AI
Adapter is a structural design pattern that allows objects with incompatible interfaces to work together. It acts as a mediator, transforming the interface of one class into the interface expected by another class.
It is used when:
- You need to use an existing class, but its interface does not match your needs.
- You need to create a class that interacts with several existing classes with different interfaces.
There are two main types of implementation:
- Class Adapter (via inheritance): The adapter inherits from the class being adapted and implements the target interface.
- Object Adapter (via composition): The adapter contains an instance of the class being adapted and implements the target interface, delegating calls to the adapted object.
Example of an object adapter:
// Target interface
interface Target {
void request();
}
// Adaptee with incompatible interface
class Adaptee {
public void specificRequest() {
System.out.println("Specific request from Adaptee");
}
}
// Adapter implementing Target and using Adaptee
class Adapter implements Target {
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
@Override
public void request() {
// Transforming request() call to specificRequest() of Adaptee
adaptee.specificRequest();
}
}
// Usage example
public class Client {
public static void main(String[] args) {
Adaptee adaptee = new Adaptee();
Target target = new Adapter(adaptee); // Using the adapter
target.request(); // Calling method via the target interface
}
}
Advantages of the adapter:
- Allows using existing classes without modifying their source code.
- Improves code reusability.
- Simplifies integration of classes with incompatible interfaces.