The Adapter Pattern converts
the interface of a class
into another interface the clients expect
. Adapter lets
classes work together that couldn’t otherwise because of
incompatible interfaces
.
Let's make things more clear!
- Target interface: the interface that the client expect
- Adapter : an intermediary class that converts the interface of one class into another class.
- Adaptee : the interface we want to work with (deal with / access it).
- Adapter class
implements
ITargetInterface and override its methods - Adapter class
has an
Instance of Adaptee class (composition)
we use the instance of Adaptee to access its specific methods
package adapter;
public class Adapter implements ITargetInterface {
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
@Override
public void method1() {
adaptee.Specific_method1();
}
@Override
public void method2() {
adaptee.Specific_method2();
}
}
- Identify the interface expected by the client class (the Target interface).
- Create a class (the Adaptee class) that has a method with a different interface than the one expected by the client.
- Create an Adapter class that implements the Target interface and has a reference to an instance of the Adaptee class.
- The Adapter class should delegate method calls from the Target interface to the Adaptee class's method.
- The client class should work with the Target interface, and the Adapter class should be used to instantiate the Adaptee class and provide the appropriate interface for the client.