2 added language tag
| link
source | link

Creating widgets, setting/getting data from them - Pattern problem

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();
    } else if (type == DataType.Choice) {
        widget = new ChoiceWidget();
    } else if (type == DataType.MultiText)
        widget = new ComboWidget();
    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)
    // ...
    // 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)

    Data getData() {
        Data data;
        // set data
        return data;

    Widget widget() {
        return this.widget;