Reputation: 13575
I heard that it is better to separate data and GUI. For examples, I have some data. It is hierarchical with abstract base and derived class for concrete types, like
class Data {};
class ConcreteDataA : public Data {};
class ConcreteDataB : public Data {};
And I also have its hierarchical GUI (for example dialog)
class DataDialog {};
class ConcreteDataADialog : public DataDialog {};
class ConcreteDataBDilaog : public DataDialog {};
And I want create a data dialog object from a data object. If the data object is ConcreteDataA, ConcreteDataADialog is created, if B, B dialog is created. There is an easy way to do it by adding a virtual function in class Data like
virtual DataDialog* CreateDialog()
But if I add this function in the data class. it seems to violate the data/GUI separation principle. The second way is to build a global CreateDialog function, and create dialogs according to the dynamic_cast type of data object. This way is also not good for many maual ifs. Any other way to implement it? Or in practice, the first way is also okay? Thanks a lot!
One of my friends told me to use reflection. I think this should work.
Upvotes: 3
Views: 212
Reputation: 22389
It seems that you're looking for an Abstract Factory.
An Abstract Factory is a design pattern in which different types of objects can be created depending on the argument. So in this example, the factory will create a ConcreteDataADialog
or a ConcreteDataBDilaog
depending on the type of the data.
Code sketch:
class DialogFactory {
public:
virtual Dialog* createDialog() = 0;
};
class ADialogFactory : public DialogFactory {
public:
Dialog* createDialog() {
return new ADialog();
}
};
class BDialogFactory : public DialogFactory {
public:
Dialog* createDialog() {
return new BDialog();
}
};
class Application {
Dialog* createSpecificDialog(Data data) {
if (data.isA()) {
return new ADialogFactory().createDialog();
} else {
return new BDialogFactory().createDialog();
}
}
Upvotes: 3