演化架构与紧急设计: 测试驱动设计,第 2 部分
2009-11-05 00:00:00 来源:WEB开发网
清单 9. 数字分类程序的完整 TDD 版本public class Classifier6 {
private Set<Integer> _factors;
private int _number;
public Classifier6(int number) {
if (number < 1)
throw new InvalidNumberException(
"Can't classify negative numbers");
_number = number;
_factors = new HashSet<Integer>();
_factors.add(1);
_factors.add(_number);
}
private boolean isFactor(int factor) {
return _number % factor == 0;
}
public Set<Integer> getFactors() {
return _factors;
}
private void calculateFactors() {
for (int i = 2; i < sqrt(_number) + 1; i++)
if (isFactor(i))
addFactor(i);
}
private void addFactor(int factor) {
_factors.add(factor);
_factors.add(_number / factor);
}
private int sumOfFactors() {
int sum = 0;
for (int i : _factors)
sum += i;
return sum;
}
public boolean isPerfect() {
calculateFactors();
return sumOfFactors() - _number == _number;
}
}
更多精彩
赞助商链接