我试图避免代码看起来像下面的问题:
If(object Is Man)
Return Image("Man")
ElseIf(object Is Woman)
Return Image("Woman")
Else
Return Image("Unknown Object")
我想我可以通过方法的重载做到这一点,但它总是挑选最小派生类型,我假设这是因为重载是在编译时确定的(与重写不同),因此只能在以下代码中假定基类:
代码结构:
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)
代码执行(重点班):
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)// This is always used
{
Image img = new Image("Unknown object");
return img;
}
public static Image GetImageForObject(Man man)
{
if(man.Age < 18)
return new Image("Image of Boy");
else
return new Image("Image of Man");
}
public static Image GetImageForObject(Woman woman)
{
if (woman.Age < 70)
return new Image("Image of Woman");
else
return new Image("Image of Granny");
}
}
我的情景: 基本上我创建一个游戏,并希望去耦真实世界的类(如男性),从屏幕上的课程(一个人的图像)。真实世界的物体应该没有关于它在屏幕上的表示的知识,表示将需要知道真实的物体(知道该人有多老,因此绘制了多少皱纹)。如果RealObject是一个未知类型,我希望有一个回退的地方,它仍然会显示一些东西(比如一个大的红十字)。
请注意,此代码不是我正在使用的,它是一个简化的版本,可以让问题保持清晰。如果适用,我可能需要稍后添加详细信息,我希望此代码的解决方案也可以在应用程序中使用。
什么是最优雅的方式来解决这个问题? - 如果RealObject本身没有掌握应该如何表示的信息。 XNA游戏是一个概念验证,它非常强大,如果证明可行,将从2D更改为3D(可能支持低端计算机)。
为什么你反对让RealObjects参考图像? – David 2011-05-03 15:29:08
要与“单一责任”保持一致。有人可能会争辩说,一个物体应该知道它的外观,但这对课程没有任何好处(除非他真的很丑,然后他可能想知道..?)。 – Lee 2011-05-03 22:31:31