【发布时间】:2014-06-18 17:01:41
【问题描述】:
我正在制作一个玩家可以点击操作按钮的游戏。此操作按钮将根据上下文执行完全不同的操作。
function doAction() {
if (standingOnItem) {
if (itemOnGround === POTION) {
if (equippiedItem === POTION) {
// mix potions
return;
}
if (equippiedItem === TORCH) {
// boil potion
return;
}
// pick up potion
}
if (itemOnGround === CHEST && equippedItem === KEY) {
// open chest
}
return;
}
if (equippedItem === POTION) {
// put potion on the ground
}
if (equippedItem === TORCH) {
// put out torch and drop it on the ground
}
if (standingOnStaircase && equippedItem === KEY) {
// move down one level
}
}
以上只是示例代码,但在我的游戏中,doAction 函数已经包含 50 个或更多条件。仅仅知道以什么顺序放置它们已成为我添加的每一个新事物的问题。问题是所有不同的组合或多或少都有独特的作用。
如何以更好的方式重构它?我可以使用任何特定的设计模式吗?
【问题讨论】:
-
如果您要测试同一个变量的不同值,您可以从使用
switch语句开始。
标签: javascript refactoring conditional conditional-statements