Skip to content

Instantly share code, notes, and snippets.

@up1
Last active August 29, 2015 14:07
Show Gist options
  • Save up1/9de38b23137ca3d77cb2 to your computer and use it in GitHub Desktop.
Save up1/9de38b23137ca3d77cb2 to your computer and use it in GitHub Desktop.
Demo :: No-IF
public static RegisterRule newInstance(String validatorRule) {
if ("NameEmptyRule".equals(validatorRule)) {
return new NameEmptyRule();
} else if ("NameFormatRule".equals(validatorRule)) {
return new NameFormatRule();
} else if ("EmailEmptyRule".equals(validatorRule)) {
return new EmailEmptyRule();
}
return null;
}
public static RegisterRule newInstance(String validatorRuleClass){
return (RegisterRule) Class.forName(validatorRuleClass).newInstance();
}
static Map<String , RegisterRule> ruleMapper = new HashMap<String, RegisterRule>() {
{
put("NameEmptyRule", new NameEmptyRule());
put("NameFormatRule", new NameFormatRule());
put("EmailEmptyRule", new EmailEmptyRule());
}
};
public static RegisterRule newInstance(String validatorRule) {
return ruleMapper.get(validatorRule);
}
enum RegisterType {
NameEmptyRule {
public RegisterRule create() {
return new NameEmptyRule();
}
},
NameFormatRule {
public RegisterRule create() {
return new NameFormatRule();
}
},
EmailEmptyRule {
public RegisterRule create() {
return new EmailEmptyRule();
}
};
public RegisterRule create() {
return null;
}
}
public static RegisterRule newInstance(RegisterType registerType) {
return registerType.create();
}
@Test
public void validInput() {
User user = new User();
user.setName("Somkiat");
user.setEmail("[email protected]");
user.setAge(30);
RuleFactory.newInstance("demo.validate.refactor.NameEmptyRule").validate(user);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment