This question is kind of continuation to my earlier post: http://stackoverflow.com/questions/944824/visitor-pattern-implementation-in-java-how-does-this-look
I got a bit confused while refactoring my code. I am trying to convert my visitor pattern (explained in the prior post) into a composite strategy pattern. I am trying to do something like this:
public interface Rule {
public List<ValidatonError> check(Validatable validatable);
}
Now, I would define a Rule like this:
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.
}
}
Now, I could have two different types objects to be validated. These two could be completely different: Say I have a Store that is Validatable
, and then a Schedule
which is Validatable
. Now, if I would write a composite that would look like this:
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();
}
}
I would define an enum
that defines what set of checks go where...
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
}
and finally, I would use it like this:
Validator validator = new Validator(ValidatorType.STORE_VALIDATOR);
for (Store store : stores) {
validator.check(store);
}
I have a strange feeling that my design is flawed. I am not liking the idea that my Rule interface expects a Validatable
. Could you please suggest how I would improve this?
Appreciate your help.