What if a class exists that provides the desired functionality but doesn't implement the desired interface?
For example, in our cart example, suppose a legacy Print class existed:
class Print {
private double price;
private Artist artist;
public double getPrice() {
if (artist.isFamous()) {
return 10 * price;
} else {
return price;
}
}
}
Assume further that we cannot modify this code either because the source code is unavailable or because the class is being shared.
We can wrap the legacy class inside of an adapter that implements the desired interface:
class PrintAdapter implements Item {
private Print print;
public PrintAdapter(Print p) {
print = p;
}
public double getValue() {
return print.getPrice();
}
}
Alternatively, we can use inheritance:
class PrintAdapter extends Print implements Item {
public double getValue() {
return getPrice();
}
}