if-statement - 如何重构深度嵌套的函数?
问题描述
我的代码目前如下所示:
If (case = 1)
{
If (option = 1)
{
If (otherOption = 1)
;do something
else if (otherOption = 2)
;do something
else if (otherOption = 3)
;do something
}
else
{
If (otherOption = 1)
;do something
else if (otherOption = 2)
;do something
else if (otherOption = 3)
;do something
}
}
else if (case = 2)
{
If (option = 1)
{
If (otherOption = 1)
;do something
else if (otherOption = 2)
;do something
else if (otherOption = 3)
;do something
}
else
{
If (otherOption = 1)
;do something
else if (otherOption = 2)
;do something
else if (otherOption = 3)
;do something
}
}
else if (case = 3)
{
If (option = 1)
{
If (otherOption = 1)
;do something
else if (otherOption = 2)
;do something
else if (otherOption = 3)
;do something
}
else
{
If (otherOption = 1)
;do something
else if (otherOption = 2)
;do something
else if (otherOption = 3)
;do something
}
}
显然可怕且难以维护。我想在此之上添加另一个超级 If 语句,它将这棵树拆分 6 次。每个 ;do something 都执行一行代码。
关于如何重构这个怪物的任何帮助?我写了很多看起来像这样的代码,我每次都害怕使用它。我需要一种新的方法来解决这些问题。扩展此代码的功能需要大量工作。
解决方案
即使您没有指定应用程序的上下文,这似乎也是一个可以利用Strategy Pattern应用程序的场景。
您发布的代码可以设置为Context对象,负责控制外部 if-else 语句的更高级别条件。在 if-else 语句的每个块中,可以使用ConcreteStrategy对象(通常实现Strategy接口)
加载特定行为。
这种模式可以重复用于内部 if-else 块。
例子
考虑一个角色在 2D 地图周围移动的游戏。根据其生命指标(例如 0-200),如果他分别处于疲倦、正常或超级状态,它可以移动 2、5、8 格。
Character对象的行为类似于“策略模式的上下文”,并且他负责哪种MoveStrategy适合该情况。赋予正确的MoveStrategy对象并通过转发方法move()到 Character 的move()方法来调用.
示例的 Java 实现提示:
public class Character{
private int life=100;
private int x=0
private int y=0;
private MoveStrategy strategy=new DefaultStrategy();
public int getLife(){
return life;
}
public void setLife(int value){
this.life=value;
}
public void move(){
if(life<30)
strategy=new TiredStrategy();
else if(life > 100)
strategy=new SuperStrategy();
else
strategy=new DefaultStrategy();
strategy.move();
}
}
public interface MoveStrategy{
public abstract void move();
}
public DefaultStrategy implements MoveStrategy{
public void move(){
System.out.println("Move character of 5 tiles");
}
}
public TiredStrategy implements MoveStrategy{
public void move(){
System.out.println("Move character of 2 tiles");
}
}
public SuperStrategy implements MoveStrategy{
public void move(){
System.out.println("Move character of 8 tiles");
}
}
推荐阅读
- node.js - 读取 HTTP AD 登录的授权响应
- swift - 如何在文本 UILabel 周围实现粗描边边框
- c# - dotnet 标准中的内容协商
- swift - 在 LazyVStack 中使用带有 AsyncImage 的 VStack 会导致图像在滚动时重新加载
- javascript - 按字母顺序对对象数组进行排序并删除重复项
- node.js - nodejs中的setTimeout和“this”关键字
- java - 如何从流集合中删除最后一个元素(DockerClient)
- python - 将numpy数组重置为零的最快方法?
- c# - 如何使用 C# 检测证书链不完整的证书?C# dotnet core 说它们是有效的而不是无效的
- javascript - 我的 2 指针算法的时间复杂度