Consider you got several validations. Those validations should only take effect if the object to be inspected is of a certain type. Why would I use a chain of responsibility over a switch-statement?
Example with chain of responsibility
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());
}
}
}
The validatorFactory creates the chain of Validators. One validator would look like
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);
}
Example with switch-statement
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
}
}
}