我試圖避免代碼看起來像下面的問題:
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