Let's consider a simplified MVC architecture, where Model operates on different types of Confections. There are different subtypes of Confection
class, such as Candy
, Cookie
, Doughnut
, etc. Every subtype, in turn, has different sets of properties, like size
, color
, shape
and so on.
For instance, that's one implementation of Candy
class:
class Candy extends Confections {
public enum Size {
LARGE,
MEDIUM,
SMALL,
}
public enum Color {
RED,
GREEN,
YELLOW,
}
private Size size;
private Color color;
...
}
Now the Model wants to update the View with a new set of Confections to display. Let's say that the only thing View needs to get the picture of a Confection
is a string representation of its type and properties, e.g. "candy_red_large"
. The dumbest thing to do this is to have a number of instanceof
branches and switch
es for types inside the View:
if (confection instanceof Candy) {
result.append("candy");
switch ((Candy) (confection).color) {
case RED:
result.append("_red");
break;
...
}
...
} else ...
Besides this monster is large and ugly, it also doesn't benefit from encapsulation and OOP. Let's consider a better way of doing this by providing each Confection
subclass with a method like toString()
, which will return the desired string representation. The only problem I see in this approach is some kind of architectural "trade-off" when Model is actually aware of View implementation details having toString
method, which is useless from Model's point of view.
What would be the best approach or design patterns to use in such case for mapping diverse data from Model to View representation?
Aucun commentaire:
Enregistrer un commentaire