Say that there are multiple classes {C1, C2, ...} which implement an interface I, containing, among other things, methods called getColor() and getName(). Every instance of C1 returns the same value when getColor() and getName() are called, same with C2 and all of the other classes that implement I. The implementations of getColor() and getName() in the C1 class might look like:
public Color getColor() {
return Color.RED;
}
public String getName() {
return "C1!!!";
}
All objects implementing the interface I can be added to and drawn to a screen. Suppose, however, that the way in which those objects are added, is through a different screen, with buttons on it. When one of those buttons is clicked, it signals to the application that the type of object associated with the clicked should be added to the screen.
If the goal is to label the button associated with C1 with the String returned by C1's getName() and color the button with the Color returned C1's getColor(), one could instantiate a new instance of C1, and then retrieve its name and color to customize its associated button:
...
I instance = new C1();
Button C1Button = new Button();
C1Button.setLabel(instance.getName());
C1Button.setColor(instance.getColor());
...
... and then instantiate a new instance of C2 and C3 and ... and C50, following the same process as with C1.
This seems rather dirty though, the classes are no longer being instantiated for the sake of fulfilling the other methods in I, but just to obtain the color and name properties for the buttons. Furthermore, that would be a awful lot of code. Can anyone provide suggestions as to how the color and name properties could be decoupled from the classes implementing I, so as to reduce the length of code required if the number of classes implementing I grows dramatically past two? Are there any specific design patterns that might be used to resolve this?
Aucun commentaire:
Enregistrer un commentaire