Java 中的 Switch Case 语句是否有任何替代方案?任何好的设计模式?我的 Switch case 语句增加如何避免 [英] Is there Any Alternative for Switch Case Statements in Java ? Any Good Design Pattern ? My Switch case Statement Increasing How to Avoid
问题描述
在代码下面,我写了为每个条件执行 switch-case 语句.现在我正在考虑删除 switch-case 语句并应用一些设计模式来解决这个问题.//主要迭代 - 对于每张纸for (Entry>> entry : testCaseSheetsDataMap.entrySet()) {
Below Code, I wrote to execute the switch-case statement, for each condition. Now I am thinking to remove the switch-case statement and apply some design pattern to overcome this issue. // main iteration - for every sheet for (Entry>> entry : testCaseSheetsDataMap.entrySet()) {
String sheetNameKey = entry.getKey().trim();
String testCaseName = testCaseSheetMasterMap.get(sheetNameKey).trim();
List<Map<String, Object>> executableRowsList = new ArrayList<Map<String, Object>>();
executableRowsList = entry.getValue();
CitiMainAuxiliary auxiliary = new CitiMainAuxiliary();
switch (testCaseName) {
case "Anonymous Mode Log In":
auxiliary.runAllLogin(executableRowsList, testCaseName, Constants.ANONYMOUS);
break;
case "Login Mode":
auxiliary.runAllLogin(executableRowsList, testCaseName, Constants.LOGIN);
break;
case "Cookied Mode Login":
auxiliary.runAllLogin(executableRowsList, testCaseName, Constants.COOKIED);
break;
case "OBO Mode Login":
auxiliary.runAllLogin(executableRowsList, testCaseName, Constants.OBO);
break;
case "Anonymous Mode Megamenu":
auxiliary.runMegaMenu(executableRowsList, testCaseName, Constants.ANONYMOUS);
break;
case "Login Mode Megamenu":
auxiliary.runMegaMenu(executableRowsList, testCaseName, Constants.LOGIN);
break;
case "Cookied Mode Logon - Megamenu Check":
auxiliary.runMegaMenu(executableRowsList, testCaseName, Constants.COOKIED);
break;
case "OBO Logon - Megamenu Check":
auxiliary.runMegaMenu(executableRowsList, testCaseName, Constants.OBO);
break;
}
} // end-for testCaseSheetsDataMap
推荐答案
如前所述,您可以使用 polymorphism
和 Strategy
模式.
As was mention you can use polymorphism
and Strategy
pattern.
例如,您可以创建 Map
并填充它
For example you can create Map<String, BiConsumer<CitiMainAuxiliary, List<Map<String, Object>>> strategies
and populate it
strategies.put("Anonymous Mode Log In", (aux, list)-> aux.runAllLogin(list,...))
之后,您可以使用代替 switch 语句strategy = strategy.get(testCaseName);strategy.accept(...)
After that instead of switch statement you can use
strategy = strategies.get(testCaseName);
strategy.accept(...)
如果您不能使用 Java 8,您可以创建一个接口并使用 Map
而不是 BiConsumer 的映射.也许接口的实现更好,因为在每个特定的类中你都可以初始化你的常量,比如 COOKIED
或 OBO
If you can't use Java 8 you can create an Interface and use Map<String, YourInterface>
instead of map of BiConsumer. Maybe the implementation with interfaces is better, because in every particular class you can initialize your Constants, like COOKIED
or OBO
这篇关于Java 中的 Switch Case 语句是否有任何替代方案?任何好的设计模式?我的 Switch case 语句增加如何避免的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!