I have a model view architecture. I want to create a view object from a model object.
Here is a basic example.
How do i specify the type of my model objects: enums (but then they are not extendable), ints (but then easy to get messed up) …
class ModelA
{
ModelA(int a);
}
class ModelB : public ModelA
{
ModelB(int a,int b);
}
class ViewModelA
{
ViewModelA(ModelA* ma);
}
class ViewModelB : public ViewModelA
{
ViewModelB(ModelB* mb);
}
class ViewFactory
{
ModelA * createFromModel(ModelA *ma)
{
// Now what is the best way to store type ???
// Used an integer and overload a static method getType()
// Or use an enum?
switch(ma.type)
{
}
}
}
int main(int argc, char *argv[])
{
ModelA *ma = new ModelA(10);
ModelA *mb = new ModelB(10,11);
ViewFactory myFactory;
ViewModelA *va = myFactory.createFromModel(ma);
ViewModelB *vb = myFactory.createFromModel(mb);
//va should be a model of ViewModelA and vb a model of ViewModelB
}
IMHO, from your question and comment on other answer, you can also use Visitor pattern here.
Read about it here or here
So, the model hierarchy would be visited by the
Visitor.The responsibility of the
Visitorwill be to create appropriateViewobject for the visitedModeltype.Then you do not need to store/declare model type.
Working code: Also live here: http://ideone.com/9A5bJ