我在java中有以下if-else分支。修改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;}
如何將此代碼修改爲戰略模式?
我在java中有以下if-else分支。修改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)));
}
}
你必須考慮面向對象編程。使用多態性。 對於戰略模式, 定義接口併爲實現接口的類提供不同的實現。選擇上下文並多級決定班級。 http://en.wikipedia.org/wiki/Strategy_pattern
但是,對於您的if-else
正確的模式對應於'工廠模式'。 http://en.wikipedia.org/wiki/Factory_method_pattern
可以代替你可以考慮使用枚舉和switch語句?如果您需要更換底層實施,戰略模式將有意義。經典示例將是不同的排序算法。 – CoolBeans