我在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