mardi 8 septembre 2015

What design pattern should I use to support behavior that varies "parallel" to a class hierarchy?

I have an ISpaceObject interface in my 4X game with abstract Vehicle and StellarObject classes implementing it; each of those has classes inheriting from it (e.g. Ship, Base, Fighter for Vehicle and Planet, Star, Storm for StellarObject). I want to be able to display icon and portrait pictures for each type of object. I have graphics code (e.g. an Icon property) in the individual classes, but it's specific to WinForms and I want to write a WPF port of my app. I don't want to have a WinFormsIcon, WpfIcon, etc. property in each of my classes; that would be kind of silly, and I'm sure putting the WinForms code in there in the first place was a mistake. How do I do parallel behaviors like this without resorting to code like the following:

if (o is Ship)
    // get ship graphic
else if (o is Base)
    // get base graphic
else if (o is Fighter)
    // get fighter graphic

etc?

Aucun commentaire:

Enregistrer un commentaire