我在C#/ Winforms中有一個應用程序,它允許用戶在網格上放置對象來爲遊戲創建關卡。它有幾個工具來放置瓷磚/燈/門/實體等。目前,我只是使用枚舉來存儲當前選定的工具並使用switch語句來運行每個工具代碼。由於我一直在嚮應用程序添加更多工具,因此它開始獲得像意大利麪一樣的大量重複代碼。重構C中的大開關的建議#
這裏是按下鼠標功能的縮減版本,在我的編輯器類:
public void OnEditorViewMouseDown(Point mousePos)
{
// Check if the click is out of bounds.
if (IsLocationOOB(mousePos)) return;
if (CurrentTool == ToolType.GroundTile)
{
// Allow drags along whole tiles only.
m_DragManager.DragType = DragManager.DragTypeEnum.Tile;
m_DragManager.StartDrag(mousePos);
}
else if (CurrentTool == ToolType.WallTile)
{
// Allow drags along grid edges only.
m_DragManager.DragType = DragManager.DragTypeEnum.Edge;
m_DragManager.StartDrag(mousePos);
}
else if (CurrentTool == ToolType.PostTile)
{
// Allow drags along grid points only.
m_DragManager.DragType = DragManager.DragTypeEnum.Point;
m_DragManager.StartDrag(mousePos);
}
else if (CurrentTool == ToolType.AreaLight)
{
// Allow drags anywhere. ie. not snapped to the grid in some way.
m_DragManager.DragType = DragManager.DragTypeEnum.FreeForm;
m_DragManager.StartDrag(mousePos);
}
else if (CurrentTool == ToolType.PointLight)
{
m_CurrentWorld.AddLight(TranslateToWorldCoords(mousePos));
}
else if (CurrentTool == ToolType.PlaceEntity)
{
m_CurrentWorld.PlaceEntity(TranslateToWorldCoords(mousePos));
}
}
的開關在其他幾項功能(的OnMouseMove,OnMouseUp)使用,這似乎是壞的設計(大開關複製幾個功能)。任何建議以更清潔和更可擴展的方式重構這樣的東西?我目前正在考慮擁有基類Tool
類,並讓每個工具都有自己的類來覆蓋它使用的函數(OnMouseDown()等)。這聽起來合理嗎?
感謝您的閱讀。
是啊,這肯定是我在想什麼。這也被稱爲戰略模式,如rjohnston的回答所述 – zonkflut 2009-06-03 00:32:27