只有第二个包含状态。
就个人而言,我会静态使用第一个,比如
class UserValidator{
private UserValidator() { } // no constructor
public static void Validate(Request request, Response response){
// some validation logic on request
// if fails, add the message to response.
}
}
但是,存储结果有一个优势——您可以一次又一次地运行它,而无需实际运行它。
class UserValidator {
public static enum ValidatorState { NOT_RUN, PASSED, FAILED }
private ValidatorState state = NOT_RUN;
private final Request request;
private final Response response;
public UserValidator(Request request, Response response) {
this.request = request;
this.response = response;
}
public ValidatorState validate() {
if(state != NOT_RUN) return state;
if(blah blah)
state = PASSED;
else
state = FAILED;
return state;
}
}
要获得各种验证器的列表,您将需要某种接口来执行该操作。
public interface Validator {
boolean validate(Request request, Response response);
}
然后,您将创建一个包含所有验证的静态方法库。请注意,这些都是虚构的示例,但包含一些真实世界的逻辑。
public class ValidationLibrary {
private ValidationLibrary() { }
public boolean validateUsername(Request request, Response response) {
String name = request.getProperty("username");
if(name.length() < 3) return false;
if(name.length() > 12) return false;
if(name.equals(name.reverse()) return false; // who knows?
return true;
}
public boolean validateSecurity(Request request, Response response) {
// what page is the user trying to reach?
SecurityRealm realm = SecurityRealm.realmForPage(request.getProperty("page"));
String username = request.getProperty("name");
return realm.allows(username);
}
}
稍后如果您需要多个验证器,您可以简单地执行此操作
List<Validator> validators = new ArrayList<Validator>();
validators.add(new Validator(){
public boolean validate(Request req, Response res) { ValidationLibrary.validateUsername(req,res); }
});
validators.add(new Validator(){
public boolean validate(Request req, Response res) { ValidationLibrary.validateSecurity(req,res); }
});
然后,当您收到请求时,您只需执行以下操作即可对其进行验证:
for(Validator v : validators) if(!v.validate(request,response)) return false;