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
}
}
}
Because in a chain of responsibility you don't need to know who does what up front in the caller. The logic of decide when you are about to run your piece of code in a chain is owned by you and the rest of the code can ignore it. This allow to encapsulate specific logic in the right place. Servlet filters are a good example of this
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With