My issue is that I have a concrete implementation which implements two different interfaces. In the spirit of Dependency Inversion Principle, I would like clients to this class to only depend on an interface and not the concrete implementation. However, as this class uniquely implements these two interfaces; it seems to me that all clients will need to program to this concrete implementation.
Take the example below: I have a Restaurant class which for the most part only needs to interact with implementations of the Pizza interface. However, the CanadianPizza class also implements the Canadian interface, with the intention that every time someone serves this Pizza they must apologize, it seems like my Restaurant class would need to have some coupling with the concrete impl (see below).
Looking for ways to avoid depending on concrete implementations with classes that are a unique composition of multiple interfaces.
interface Pizza {
void bake()
void addToppings()
void rollDough()
}
interface Canadian {
void apologize()
}
class CanadianPizza implements Pizza, Canadian {
@Override
void bake() { ... }
@Override
void apologize { ... }
}
class Restaurant {
private final Pizza mPizza;
constructor(Pizza pizza) {
mPizza = pizza;
}
void serveFood() {
mPizza.rollDough()
mPizza.addToppings()
doSomethingWithPizza()
// But I also need to know if my Pizza is Canadian
if (mPizza instanceof CanadianPizza) {
((CanadianPizza) mPizza).apologize()
}
}
}
Aucun commentaire:
Enregistrer un commentaire