Problem
I am trying to avoid code that looks like this:
If(object Is Man) Return Image("Man") ElseIf(object Is Woman) Return Image("Woman") Else Return Image("Unknown Object")
I thought I could do this with the method overload, but it always selects the least derived type, I assume that this is because the overload is determined at compile time (as opposed to overriding), and therefore only the base class can be accepted in following code:
Code structure:
NS:Real RealWorld (Contains a collection of all the RealObjects) RealObject Person Man Woman NS:Virtual VirtualWorld (Holds a reference to the RealWorld, and is responsible for rendering) Image (The actual representation of the RealWorldObject, could also be a mesh..) ArtManager (Decides how an object is to be represented)
Code implementation (key classes):
class VirtualWorld { private RealWorld _world; public VirtualWorld(RealWorld world) { _world = world; } public void Render() { foreach (RealObject o in _world.Objects) { Image img = ArtManager.GetImageForObject(o); img.Render(); } } } static class ArtManager { public static Image GetImageForObject(RealObject obj)
My scenario: In essence, I create a game and want to separate the classes of the real world (for example, a person) from the classes on the screen (image of a person). An object of the real world should not know about this screen representation, the idea should know about the real object (know how old the man is, and therefore how many wrinkles are drawn). I want to have a backup, where if RealObject is of an unknown type, it still displays something (like a big red cross).
Please note that this code is not what I use, it is a simplified version to keep the question clear. I may need to add details later, if applicable. I hope that the solution to this code will also work in the application.
What is the most elegant way to solve this problem? - Without RealObject itself, containing information on how it should be presented. The XNA game is a proof of concept, which is very difficult, and if it turns out to be feasible, it will be changed from 2D to 3D (perhaps supported as for lower computers).