引自免费微信小程序:皆我百晓生
为了简化这个问题并构建一个高效的解决方案,我们可以设计一个实体类GrossMarginRule来存储毛利率规则,其中包含边界值和边界类型(开区间或闭区间)。然后,利用这些信息,我们可以在添加新规则时检查与现有规则的冲突。
首先,定义GrossMarginRule实体类:
public class GrossMarginRule {
private double lowerBound;
private boolean lowerInclusive; // true for '[', false for '('
private double upperBound;
private boolean upperInclusive; // true for ']', false for ')'
public GrossMarginRule(double lowerBound, boolean lowerInclusive, double upperBound, boolean upperInclusive) {
this.lowerBound = lowerBound;
this.lowerInclusive = lowerInclusive;
this.upperBound = upperBound;
this.upperInclusive = upperInclusive;
}
// Getters and setters
public double getLowerBound() { return lowerBound; }
public boolean isLowerInclusive() { return lowerInclusive; }
public double getUpperBound() { return upperBound; }
public boolean isUpperInclusive() { return upperInclusive; }
// Check if a value fits within the rule's range
public boolean isValueInRange(double value) {
if (lowerInclusive) {
if (upperInclusive) {
return value >= lowerBound && value <= upperBound;
} else {
return value >= lowerBound && value < upperBound;
}
} else {
if (upperInclusive) {
return value > lowerBound && value <= upperBound;
} else {
return value > lowerBound && value < upperBound;
}
}
}
// Check if another rule overlaps with this rule
public boolean doesOverlap(GrossMarginRule other) {
return this.isValueInRange(other.getLowerBound()) || this.isValueInRange(other.getUpperBound())
|| other.isValueInRange(this.getLowerBound()) || other.isValueInRange(this.getUpperBound());
}
}
接下来,创建一个GrossMarginRuleManager类,用于管理规则列表,并提供添加规则的方法,同时检查是否与已有规则冲突:
import java.util.List;
import java.util.ArrayList;
public class GrossMarginRuleManager {
private List<GrossMarginRule> rules;
public GrossMarginRuleManager() {
this.rules = new ArrayList<>();
}
public void addRule(GrossMarginRule newRule) throws Exception {
for (GrossMarginRule existingRule : rules) {
if (newRule.doesOverlap(existingRule)) {
throw new Exception("New rule overlaps with an existing rule.");
}
}
rules.add(newRule);
}
// Other methods like getting all rules, removing rules etc.
}
使用示例:
public class Main {
public static void main(String[] args) {
GrossMarginRuleManager manager = new GrossMarginRuleManager();
try {
manager.addRule(new GrossMarginRule(20, true, 30, false));
// Attempt to add a conflicting rule
manager.addRule(new GrossMarginRule(20, false, 25, true)); // This should not throw an exception
manager.addRule(new GrossMarginRule(20, true, 25, true)); // This should throw an exception
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
通过这种方式,你不仅能够清晰地管理毛利率规则,还能够有效地检测和防止规则间的冲突。这种方法减少了需要编写的逻辑判断量,并提高了代码的可读性和维护性。