Chain of responsibility : Chain of Responsibility Patterns « Design Pattern « Java Tutorial






// Carries the result data and whether the strategy was successful:

class Document {
  public double[] data;

  public Document(double[] data) {
    this.data = data;
  }

  private boolean succeeded;

  public boolean isSuccessful() {
    return succeeded;
  }

  public void setSuccessful(boolean b) {
    succeeded = b;
  }
}

interface Format {
  Document doFormat(Document m);
}

class EnlargeFont implements Format {
  public Document doFormat(Document m) {
    System.out.println("Trying EnlargeFont algorithm");
    Document r = new Document(new double[] { 1.1, 2.2 }); // Dummy data
    r.setSuccessful(false);
    return r;
  }
}

class ChangeColor implements Format {
  public Document doFormat(Document m) {
    System.out.println("Trying ChangeColor algorithm");
    Document r = new Document(new double[] { 3.3, 4.4 }); // Dummy data
    r.setSuccessful(false);
    return r;
  }
}

class AddHeader implements Format {
  public Document doFormat(Document m) {
    System.out.println("Trying AddHeader algorithm");
    Document r = new Document(new double[] { 5.5, 6.6 }); // Dummy data
    r.setSuccessful(true);
    return r;
  }
}

class AddFooter implements Format {
  public Document doFormat(Document m) {
    System.out.println("Trying AddFooter algorithm");
    Document r = new Document(new double[] { 5.5, 6.6 }); // Dummy data
    r.setSuccessful(true);
    return r;
  }
}

class DocumentFormat {
  private static Format[] solutions = { new EnlargeFont(), new ChangeColor(), new AddHeader(),
      new AddFooter(), };

  public static Document solve(Document line) {
    Document r = line;
    for (int i = 0; i < solutions.length; i++) {
      r = solutions[i].doFormat(r);
      if (r.isSuccessful())
        return r;
    }
    throw new RuntimeException("unsolved: " + line);
  }
}

public class ChainOfResposibilityDemo {
  public static void main(String args[]) {
    Document line = new Document(new double[] { 1.0, 2.0, 1.0, 2.0, -1.0, 3.0, 4.0, 5.0, 4.0 });
    System.out.println(((Document) DocumentFormat.solve(line)).data);
  }
}








34.7.Chain of Responsibility Patterns
34.7.1.Watch What is Going On with the Chain of Responsibility Patterns
34.7.2.Chain of responsibility
34.7.3.Multiple dispatching