Allowing objects with incompatible interfaces to collaborate
Check code here
public interface Movable {
double getSpeed();// speed in MPH
}
public class Car implements Movable {
@Override
public double getSpeed() {
return 150;
}
}
public class Boat implements Movable {
@Override
public double getSpeed() {
return 300;
}
}
public interface MovableAdapter {
double getSpeed(); // speed in KM/H
}
public class MovableAdapterImpl implements MovableAdapter {
private Movable movable;
public MovableAdapterImpl(Movable movable) {
this.movable = movable;
}
@Override
public double getSpeed() {
return movable.getSpeed() * 1.60934;
}
}
To access the instance
Movable bugatti = new Car(268);
final double speedInMPH = bugatti.getSpeed();
MovableAdapter bugattiVAdapter = new MovableAdapterImpl(bugatti);
final double speedInKMH = bugattiVAdapter.getSpeed();
- whenever you want to use an existing class, but it's interface isn't compatible with the rest of the code