Multiple dispatching : Chain of Responsibility Patterns « Design Pattern « Java Tutorial






import java.util.Random;

class Result {
  private String name;

  private Result(String name) {
    this.name = name;
  }

  public final static Result LessThan = new Result("Less than"), Equal = new Result("equal"),
      GreaterThan = new Result("Greater than");

  public String toString() {
    return name;
  }
}

interface Number {
  Result compete(Number it);

  Result eval(One p);

  Result eval(Two s);

  Result eval(Three r);
}

class One implements Number {
  public Result compete(Number it) {
    return it.eval(this);
  }

  public Result eval(One p) {
    return Result.GreaterThan;
  }

  public Result eval(Two s) {
    return Result.LessThan;
  }

  public Result eval(Three r) {
    return Result.Equal;
  }

  public String toString() {
    return "One";
  }
}

class Two implements Number {
  public Result compete(Number it) {
    return it.eval(this);
  }

  public Result eval(One p) {
    return Result.Equal;
  }

  public Result eval(Two s) {
    return Result.GreaterThan;
  }

  public Result eval(Three r) {
    return Result.LessThan;
  }

  public String toString() {
    return "Two";
  }
}

class Three implements Number {
  public Result compete(Number it) {
    return it.eval(this);
  }

  public Result eval(One p) {
    return Result.LessThan;
  }

  public Result eval(Two s) {
    return Result.Equal;
  }

  public Result eval(Three r) {
    return Result.GreaterThan;
  }

  public String toString() {
    return "Three";
  }
}

class NumberGenerator {
  private static Random rand = new Random();

  public static Number newItem() {
    switch (rand.nextInt(3)) {
    default:
    case 0:
      return new Two();
    case 1:
      return new One();
    case 2:
      return new Three();
    }
  }
}

class Compete {
  public static void match(Number a, Number b) {
    System.out.println(a + " " + a.compete(b) + " vs. " + b);
  }
}

public class MultipleDispathDemo {

  public static void main(String args[]) {
    int SIZE = 20;

    for (int i = 0; i < SIZE; i++)
      Compete.match(NumberGenerator.newItem(), NumberGenerator.newItem());

  }

}








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