您可以将 Cor 模式用于验证“行为”:您的每个验证器都将实现一个基本ChainedValidator
接口(一些行为可以移动到父抽象类,因为它对于所有链成员都是相同的):
public class MyFirstValidator implements ChainedValidator{
//This CoR implementation has also a 'Composite' background
ChainedValidator nextValidator;
@Override
private void doValidate(Request request) throws ValidationException
{
if(badSituation){
//throw validation exception
}
}
@Override
public void doChainValidate(Request request) throws ValidationException
{//This method can be moved to a parent abstract class
doValidate(request);
if(nextValidator!=null){
nextValidator.doChainValidate(request);
}
}
private void attachValidator(ChainedValidator newValidator) throws ValidationException
{//same as previous method
if(nextValidator!=null){
nextValidator.attachValidator(request);
}else{
nextValidator=newValidator;
}
}
//setters & other methods
}
在您的控制器/Web 层服务类上,您可以注入第一个ChainedValidator
验证链并调用doChainValidate
:
public class WebTierService{
ChainedValidator validator;
public Response serviceMethod(Request request){
try{
//...
validator.doChainValidate(request);
//...
}catch(ValidationException e){
return Response.status(400).entity(e.getMessage()).build();
}
}
}
如您所见,逻辑是“流动的”(否 if else 检查取决于验证错误的类型)并且添加新的验证器相对简单(validator.attachValidator()
),这使得逻辑可扩展且简洁。