gpt4 book ai didi

java - 将 if-else 修改为策略模式

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:03:50 26 4
gpt4 key购买 nike

我在 java 中有以下 if-else 分支。

    if (str.equals("a")) { A;}
else if (str.equals("b")) { B;}
else if (str.equals("c")) { C;}
else if (str.length == 5) { D;}
else { E;}

如何将这段代码修改成策略模式?

最佳答案

这里是一个使用工厂的策略模式的例子:

public interface Strategy {
public Object[] execute(Object[] args);
}

public class StrategyFactory {

public enum Name {
REVERSE, STRINGIFY, DUPLICATE;
}

private StrategyFactory() {
// never instantiate; only use static factory methods
}

public static Strategy getStrategyReverse() {
return new Strategy() {
public Object[] execute(Object[] args) {
Object[] reversed = new Object[args.length];
for (int i = 0; i < args.length; i++) {
reversed[i] = args[args.length - i - 1];
}
return reversed;
}
};
}

public static Strategy getStrategyStringify() {
return new Strategy() {
public Object[] execute(Object[] args) {
String[] stringified = new String[args.length];
for (int i = 0; i < args.length; i++) {
stringified[i] = String.valueOf(args[i]);
}
return stringified;
}
};
}

public static Strategy getStrategyDuplicate() {
return new Strategy() {
public Object[] execute(Object[] args) {
Object[] duplicated = new Object[2 * args.length];
for (int i = 0; i < args.length; i++) {
duplicated[i * 2] = args[i];
duplicated[i * 2 + 1] = args[i];
}
return duplicated;
}
};
}

public static Strategy getStrategy(String name) {
return getStrategy(Name.valueOf(name));
}

public static Strategy getStrategy(Name name) {
switch (name) {
case REVERSE:
return getStrategyReverse();
case STRINGIFY:
return getStrategyStringify();
case DUPLICATE:
return getStrategyDuplicate();
default:
throw new IllegalStateException("No strategy known with name " + name);
}
}
}

public class Main {
public static void main(String[] args) {

Strategy strategy = StrategyFactory.getStrategy("DUPLICATE");
System.out.println(Arrays.toString(strategy.execute(args)));
}
}

关于java - 将 if-else 修改为策略模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6529856/

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