gpt4 book ai didi

java - 如何重构方法?

转载 作者:行者123 更新时间:2023-11-29 05:08:47 25 4
gpt4 key购买 nike

有一个给定的方法。我们如何重构它?

public void foo(Factor o){
if(o.matches(constant1)){
method1();
}else if(o.matches(constant2)){
method2();
}
}else if(o.matches(constant3)){
method3();
}
....
}

最佳答案

这就是所谓的代码味道。您可能想要使用所谓的“命令模式”,这是一种重构此代码的设计模式。现在在移动设备上,当我今天到我的办公 table 时会更新一个例子。

编辑:开始吧。

因此,命令模式是用于这种确切场景的设计模式。您首先需要做的是创建一个命令界面。

public interface MyCommand {
public void execute();
}

太棒了。接下来创建 Command 对象来保存所有方法数据。

public class Method1Command implements MyCommand {
public MyVariable var;

public Method1Command(<your arguments to create method>)
{
// instantiate your command
}

public void execute()
{
// what your current method1() is;
}
}

然后您只需在 Main 中创建某种私有(private)类来创建所有命令的 HashMap,以“ConstantX”的值作为键。

private static Map<String, MyCommand> getMyCommands()
{
Map<String, MyCommand> commandList = new HashMap<String, MyCommand>();
MyCommand c;

c = new Method1Command();
commandList.put("constant1", c);

c = new Method2Command();
commandList.put("constant2", c);

c = new Method3Command();
commandList.put("constant3", c);

return commandList();
}

然后,在重构方法中,您只需执行以下操作:

public void foo(Factor o)
{
cl.get(o).execute();
}

但是,这假设 o 内部有某种 toString 方法,或者如果您在 o 内部有一些方法可以用来获取命令,它将是这样的:cl.get(o .getMyCommand()).execute();

关于java - 如何重构方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29469108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com