这个问题是我之前帖子的延续: Java 中的访问者模式实现——这看起来如何?
我在重构代码时有点困惑。我正在尝试将我的访问者模式(在上一篇文章中解释)转换为复合策略模式。我正在尝试做这样的事情:
public interface Rule {
public List<ValidatonError> check(Validatable validatable);
}
现在,我将定义这样的规则:
public class ValidCountryRule {
public List<ValidationError> check(Validatable validatable) {
// invokeDAO and do something, if violation met
// add to a list of ValidationErrors.
// return the list.
}
}
现在,我可以验证两种不同类型的对象。这两个可能完全不同:假设我有一个 Store that is Validatable
,然后一个Schedule
which is Validatable
。现在,如果我要编写一个看起来像这样的组合:
class Validator implements Rule {
private List<Rule> tests = new ArrayList<Rule>();
public void addRule(Rule rule) {
tests.add(rule);
}
public List<ValidationError> check(Visitable visitable) {
List<ValidationError> list = new ArrayList<ValidationError>();
for(Rule rule : tests) {
list.addAll(rule.check(visitable);
}
}
public Validator(ValidatorType type) {
this.tests = type.getRules();
}
}
我会定义一个enum
定义哪些检查集去哪里......
public Enum ValidatorType {
public abstract List<Rule> getRules();
STORE_VALIDATOR {
public List<Rule> getRules() {
List<Rule> rules = new ArrayList<Rule>();
rules.add(new ValidCountryRule());
rules.add(new ValidXYZRule());
}
// more validators
}
最后,我会这样使用它:
Validator validator = new Validator(ValidatorType.STORE_VALIDATOR);
for (Store store : stores) {
validator.check(store);
}
我有一种奇怪的感觉,我的设计有缺陷。我不喜欢我的 Rule 界面需要Validatable
. 您能否建议我如何改进这一点?
感谢你的帮助。