DisplayEngine has a list of DisplayableObjects. Each DisplayableObject derived class uses a different set of data. So I have created a base class for data so that I can pass BaseData into the update for each DisplayableObject without having to know anything about derived classes of DisplayableObject and BaseData. Then in each derived DisplayableObject update function I cast to the right type of data.
The problem is this is a semantic coupling. If I pass the wrong derived data class to one of the derived DisplayableObject classes this blows up, and really the update function really CAN’T handle ALL BaseData classes like it appears to on the outside.
Essentially what is happening here is Module1 passes BaseObject to Module2. Because Module2 knows that Module2 is really passing it DerivedObject, it casts BaseObject to DerivedObject and uses data that is specific to DerivedObject.
The trouble is, I can’t figure out a way to do this any other way. How can I have a list of DisplayableObjects that each take a different set of data and have the DisplayEngine know nothing about any of the derived classes so that I can reuse the DisplayEngine in another project?
This is a bit complicated, so thank you in advance for taking a look at it.
Class DisplayEngine{
DisplayableObject displayableObjectsList[10];
BaseData *dataList[10];
// Each element in data list is updated somewhere else.
void UpdateAll(){
for(int i=0; i<10; i++){
displayableObjectsList[i].Update(dataList[i]);
}
}
}
Class DisplayableObject{
virtual void Update(BaseData bData);
}
Class BaseData {
//empty.
}
Class Data1 : BaseData{
String b;
}
Class Data2: BaseData{
int a;
}
Class DisplayableObject1: DisplayableObject{
void Update(BaseData bData){
Data1* d = (Data1*) bData;
//Do Work with d, can use d.b
}
}
Class DisplayableObject2: DisplayableObject{
void Update(BaseData bData){
Data2* d = (Data2*) bData;
//Do Work with d, can use d.a
}
}