[Design Pattern] Verhaltensmuster: Chain of Responsibility


Thomas Darimont

Premium-User
Hallo,

dieser Beitrag erklärt das Verhaltensmuster: Chain of Responsibility

Java:
package de.tutorials.design.patterns.behavioral;

public class ChainOfResponsibilityExample {
  public static void main(String[] args) {
    final IntegerMustBePositve validator = new IntegerMustBePositve(new IntegerMustBeEven(null));
    
    execute(new Runnable() {
      public void run() {
        validator.validate(10);
      }
    });
    
    execute(new Runnable() {
      public void run() {
        validator.validate(-56);
      }
    });
    
    execute(new Runnable() {
      public void run() {
        validator.validate(9);
      }
    });
    
  }
  
  private static void execute(Runnable runnable) {
    try{
      runnable.run();
    }catch(Throwable e){
      System.err.println(e.getMessage());
    }
  }

  static interface Validator<T>{
    void validate(T t);
    Validator<T> next();
  }
  
  static abstract class AbstractValidator<T> implements Validator<T>{
    private Validator<T> next;
    
    public AbstractValidator(Validator<T> next) {
      this.next = next;
    }
    
    public void validate(T t) {
      if(next() != null){
        next().validate(t);
      }
    };
    
    @Override
    public Validator<T> next() {
      return this.next;
    }
  }
  
  static class IntegerMustBePositve extends AbstractValidator<Integer>{
    public IntegerMustBePositve(Validator<Integer> next) {
      super(next);
    }

    @Override
    public void validate(Integer t) {
      super.validate(t);
      if(t < 0){
        throw new IllegalArgumentException(t + " is not positive!");
      }
      System.out.println(t + " is positive");
      
    }
  }
  
  static class IntegerMustBeEven extends AbstractValidator<Integer>{
    
    public IntegerMustBeEven(Validator<Integer> next) {
      super(next);
    }
    
    @Override
    public void validate(Integer t) {
      super.validate(t);
      if(t % 2 != 0){
        throw new IllegalArgumentException(t + " is not even!");
      }
      
      System.out.println(t + " is even");
    }
  }
}
Ausgabe:
Code:
10 is even
10 is positive
-56 is even
-56 is not positive!
9 is not even!
Gruß Tom
 

Neue Beiträge