Lets say I have a Widget
class. I also have TextWidget
, ComboWidget
, ChoiceWidget
classes that inherited from Widget
class.
I create this widgets based on the situation. After creating the widget, I just show some data on widget and get one from the user. After that the widget gets destroyed. My current code is something like this: (The code is totally arbitrary)
Widget createWidget(DataType type, Data data) {
Widget widget;
if (type == DataType.Text) {
widget = new TextWidget();
widget.setText(data.toStrig());
} else if (type == DataType.Choice) {
widget = new ChoiceWidget();
widget.setChoices(data.toChoices())
} else if (type == DataType.MultiText)
widget = new ComboWidget();
widget.setItems(data.toItems())
}
return widget;
}
After creating, I get some data from user using that widget. Then I just destroy it.
void widgetReturnPressedEvent(Widget widget) {
UserData data;
if (widget.type() == TextWidget)
data.setText(((TextWidget)widget).getText())
// ...
// You get the idea.
}
I'm using this at different parts of my program. So doing if-else every time is not a good way to handle this situation. So what should I do here? Can something like this works, or is there a good pattern for this situation?
class DataWidget {
Widget widget;
Widget createWidget(DataType type) {
Widget w;
//...
this.widget = w;
}
void setData(Data data) {
if (this.widget == TextWidget)
this.widget.setText(data.toString());
//...
}
Data getData() {
Data data;
// set data
return data;
}
Widget widget() {
return this.widget;
}
}