我有一小組驗證類,我已經創建了這些類,這些類已經很好地服務了我,但是現在我需要更新它們以處理優先級規則。如果滿足高優先級規則,那麼我不需要運行任何進一步的驗證,因爲我們只會告訴用戶一條單獨的錯誤消息,而不是將全部消息添加到用戶。Typesafe優先級規則
下面是一組類,我有:
//Rule.java
public interface Rule<T> {
List<ErrorMessage> validate(T value);
}
//ValidationStrategy.java
public interface ValidationStrategy<T> {
public List<Rule<? super T>> getRules();
}
//Validator.java
public class Validator<T> implements Rule<T> {
private List<Rule<? super T>> tests = new ArrayList<Rule<? super T>>();
public Validator(ValidationStrategy<T> type) {
this.tests = type.getRules();
}
public List<ErrorMessage> validate(T value) {
List <ErrorMessage> errors = new ArrayList<ErrorMessage>();
for (Rule<? super T> rule : tests) {
errors.addAll(rule.check(value));
}
return errors;
}
}
我有一些麻煩,修改該代碼來處理優先規則。當然,有些東西我可以修改使用,而不是引入規則引擎。
理想那麼我可以這樣創建規則:
private static final Rule<SomeClass> ensureAllFieldsNotBlank = new Rule<SomeClass>(RulePriority.HIGHEST) {
public List<ErrorMessage> check(SomeClass someClass) {
List<ErrorMessage> errors = new ArrayList<ErrorMessage>();
if (StringUtils.isBlank(someClass.getValue1())
&& StringUtils.isBlank(someClass.getValue2())
&& StringUtils.isBlank(someClass.getValue3())) {
errors.add("Provide a response for \"" + someClass.getName() + "\"");
}
return errors;
}
};
編輯更新類:
//ValidationStrategy.java
public interface ValidationStrategy<T> {
public List<Rule<? super T>> getRules(RulePriority rulePriority);
}
//RulePriority.java
public enum RulePriority { HIGHEST, DEFAULT, LOWEST; }
//Validator.java
public class Validator<T> implements Rule<T> {
private List<Rule<? super T>> tests = new ArrayList<Rule<? super T>>();
private ValidationStrategy<T> validationStrategy;
public Validator(ValidationStrategy<T> validationStrategy) {
this.validationStrategy = validationStrategy;
for (RulePriority rp : RulePriority.values()) {
this.tests.addAll(validationStrategy.getRules(rulePriority));
}
}
public List<ErrorMessage> validate(T value) {
List<ErrorMessage> errors = new ArrayList<String>();
for (RulePriority rp : RulePriority.values()) {
for (Rule<? super T> rule : validationStrategy.getRules(rp)) {
errors.addAll(rule.validate(value));
}
if (errors.size() > 0) {
break;
}
}
return errors;
}
我喜歡這種方法,但我只想指出,很容易讓`compareTo()`與`equals()`一致 - 只需調用它即可!如果他們相等返回0,否則返回任何東西,但。 – CurtainDog 2010-11-25 03:32:56