這是我的解決方案。相當詳細,但應該可以維護。
public class Interval {
final int bottom;
final int top;
final IntervalEvaluationStrategy strategy;
public Interval(final int bottom, final int top, final IntervalEvaluationStrategy strategy) {
this.bottom = bottom;
this.top = top;
this.strategy = strategy;
}
public boolean check(int value) {
return strategy.evaluate(value, bottom, top);
}
public enum IntervalEvaluationStrategy {
OPEN {
@Override
boolean evaluate(int value, int bottom, int top) {
return CLOSED.evaluate(value, bottom, top)
|| value == bottom
|| value == top;
}
},
CLOSED {
@Override
boolean evaluate(int value, int bottom, int top) {
return value > bottom
&& value < top;
}
};
abstract boolean evaluate(int value, int bottom, int top);
}
public static void main(String[] args) {
assert checkInterval(5, 5, 10, IntervalEvaluationStrategy.OPEN);
}
//helper method with example usage
public static boolean checkInterval(final int value, final int bottom, final int top, IntervalEvaluationStrategy strategy) {
final Interval interval = new Interval(bottom, top, strategy);
return interval.check(value);
}
}
「讓我們假設間隔打開」其實你的例子是一個封閉的間隔。 –
heh oops:D @ Code-Apprentice – CabDude