考虑到你有几个验证。只有当要检查的对象属于某种类型时,这些验证才会生效。为什么我要在 switch 语句上使用责任链?
责任链示例
public class Executor {
@Inject
private ValidatorFactory validatorFactory;
public void execute(Konfiguration konfig) {
List<Statement> statements = konfig.getStatements();
AbstractValidator validator = validatorFactory.create();
for (Statement statement : statements) {
if (validator.validate(statement.getType())) {
crudService.execute(statement.getSql());
}
}
}
验证器工厂创建验证器链。一个验证器看起来像
public class AddPrimaryKeyValidator extends AbstractValidator {
@Override
public boolean validate(Statement statement) {
if (SqlType.ADD_PK.getTyp().equals(statement.getType())) {
return doesTableAndPrimaryKeyExist(statement.getTabName());
}
return successor.validate(statement);
}
带有 switch 语句的示例
public void execute(Konfiguration konfig) {
List<Statement> statements = konfig.getStatements();
for (Statement statement : statements) {
switch (statement.getType()) {
case "ADD_PK":
if (doesTableAndPrimaryKeyExist(statement.getTabName())) {
frepCrudService.execute(statement.getSql());
}
// more cases
}
}
}