目前有4種組合
- 添加小時。
- 添加天數。
- 減去小時。
- 減去天數。
private String modifyDate(Character symbol, LocalDateTime date, Long digits, String period) {
switch (symbol) {
case ' ':
if (period.contains("days")) {
return date.plusDays(digits).toString();
} else {
return date.plusHours(digits).toString();
}
case '-':
if (period.contains("days")) {
return date.minusDays(digits).toString();
} else {
return date.minusHours(digits).toString();
}
default:
System.out.println("Not defined operation");
}
return "";
}
如果添加了一個新的期間(假設為years),則有必要在每種情況下添加一個新的 if 陳述句:
if (period.contains("years")) {
return date.plusYears(digits).toString();
} else if (period.contains("days")) {
return date.plusDays(digits).toString();
} else {
return date.plusHours(digits).toString();
}
此外,如果添加了新的意外情況(組合,特殊情況),則需要重復邏輯以驗證期間。
您有改進解決方案的建議嗎?模式推薦,功能介面實作,歡迎推薦。
提前致謝!
uj5u.com熱心網友回復:
Martin Fowler 的一般建議是將 Conditional 替換為 Polymorphism。
https://www.refactoring.com/catalog/replaceConditionalWithPolymorphism.html
在設計模式方面,這通常是策略模式用策略替換條件邏輯。
https://www.industriallogic.com/xp/refactoring/conditionalWithStrategy.html
如果你有一個小的、有限的條件集,我建議使用列舉來實作策略模式(在列舉中提供一個抽象方法并為每個常量覆寫它)。
我希望它可能對你有幫助。
uj5u.com熱心網友回復:
這可以通過策略模式結合列舉來解決。
https://www.tutorialspoint.com/design_pattern/strategy_pattern.htm
uj5u.com熱心網友回復:
在之前的評論中提到了很好的建議,我將添加一些細節:
- 繼續搜索“用模式替換條件”,這是一個不同的例子。
- 使用列舉的策略實作
public enum Strategy {
ADD {
@Override
public String methodImp(String daysHours, LocalDateTime date, Long plusPeriod) {
return period.contains(Enum1.DAYS.label)
? date.plusDays(plusPeriod).toString() :
date.plusHours(plusPeriod).toString();
}
},
SUBTRACT {
@Override
public String methodImp(String daysHours, LocalDateTime date, Long minusPeriod) {
return period.contains(Enum1.DAYS.label)
? date.minusDays(minusPeriod).toString() :
date.minusHours(minusPeriod).toString();
}
};
public abstract String methodImp(String daysHours, LocalDateTime date, Long timePeriod);
}
- 您可以實作 2 個列舉:
- 一個包含天/小時
public enum Enum1 {
DAYS("days"),
HOURS("hours");
public final String label;
private Period(String label) {
this.label = label;
}
}
- 一個用于數學運算子,如果您要接收一個字符,那么我建議按label搜索,下面的實作。
public enum MathOperators {
PLUS(' '),
SUBTRACT('-');
private static final Map<Character, Operator> BY_LABEL = new HashMap<>();
public final Character label;
static {
for (Operator e: values()) {
BY_LABEL.put(e.label, e);
}
}
Operator(Character label) {
this.label = label;
}
public static Operator valueOfLabel(Character label) {
return BY_LABEL.get(label);
}
}
- 最后是背景關系邏輯:
public static String contextLogic(Character mathOperator, String daysHours, LocalDateTime date, Long timePeriod) {
var value = "";
switch (Operator.valueOfLabel(operator)) {
case PLUS:
value = Strategy.ADD.operation(daysHours, date, timePeriod);
break;
case SUBTRACT:
value = Strategy.SUBTRACT.operation(daysHours, date, timePeriod);
break;
}
return value;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/402202.html
