Junior
What is the main idea of the Adapter pattern?
sobes.tech AI
Answer from AI
Allows objects with incompatible interfaces to work together by 'wrapping' the incompatible objects to provide a compatible interface.
Example:
// Incompatible interface
interface OldSystem {
void performLegacyOperation();
}
// Implementation of incompatible interface
class OldSystemImpl implements OldSystem {
@Override
public void performLegacyOperation() {
System.out.println("Executing legacy operation.");
}
}
// Target interface
interface NewSystem {
void performModernOperation();
}
// Adapter
class Adapter implements NewSystem {
private OldSystem oldSystem; // Composition: adapter contains an object of the old system
public Adapter(OldSystem oldSystem) {
this.oldSystem = oldSystem;
}
@Override
public void performModernOperation() {
// Call the old system's method through the adapted interface
oldSystem.performLegacyOperation();
}
}
// Client code using the new interface
class Client {
private NewSystem newSystem;
public Client(NewSystem newSystem) {
this.newSystem = newSystem;
}
public void executeOperation() {
newSystem.performModernOperation();
}
}
// Using the adapter
//public class Main {
// public static void main(String[] args) {
// OldSystem oldSystem = new OldSystemImpl();
// NewSystem adapter = new Adapter(oldSystem); // Creating the adapter
// Client client = new Client(adapter); // Client works with the adapted interface
// client.executeOperation();
// }
//}
- Adaptee (Adaptee): The class with an incompatible interface (
OldSystemImpl). - Target (Target): The interface expected by the client (
NewSystem). - Adapter (Adapter): The class implementing the target interface (
Adapter) and containing a reference to the adaptee object. It converts calls from the target interface into calls to the adaptee. - Client (Client): Uses the target interface to interact with objects.