001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
package composite.two;
public class ExprFactory {
  private ExprFactory() {}
  static public Expr newConst(int v) {
    return new Const(v);
  }
  static public Expr newPlus(Expr l, Expr r) {
    return new Plus(l, r);
  }
  static public Expr newMinus(Expr l, Expr r) {
    return new Minus(l, r);
  }
  static public Expr newMult(Expr l, Expr r) {
    return new Mult(l, r);
  }
  static public Expr newQuot(Expr l, Expr r) {
    return new Quot(l, r);
  }

  private static class Const implements Expr {
    private final int v;
    public Const(int v) {
      this.v = v;
    }
    public int eval() {
      return v;
    }
    public String toString() {
      return Integer.toString(v);
    }
  }

  private static class Plus implements Expr {
    private final Expr l;
    private final Expr r;
    public Plus(Expr l, Expr r) {
      if ((l == null) || (r == null)) {
        throw new IllegalArgumentException();
      }
      this.l = l;
      this.r = r;
    }
    public int eval() {
      return l.eval() + r.eval();
    }
    public String toString() {
      return l.toString() + " " + r.toString() + " +";
    }
  }

  private static class Minus implements Expr {
    private final Expr l;
    private final Expr r;
    public Minus(Expr l, Expr r) {
      if ((l == null) || (r == null)) {
        throw new IllegalArgumentException();
      }
      this.l = l;
      this.r = r;
    }
    public int eval() {
      return l.eval() - r.eval();
    }
    public String toString() {
      return l.toString() + " " + r.toString() + " -";
    }
  }

  private static class Mult implements Expr {
    private final Expr l;
    private final Expr r;
    public Mult(Expr l, Expr r) {
      if ((l == null) || (r == null)) {
        throw new IllegalArgumentException();
      }
      this.l = l;
      this.r = r;
    }
    public int eval() {
      return l.eval() * r.eval();
    }
    public String toString() {
      return l.toString() + " " + r.toString() + " *";
    }
  }

  private static class Quot implements Expr {
    private final Expr l;
    private final Expr r;
    public Quot(Expr l, Expr r) {
      if ((l == null) || (r == null)) {
        throw new IllegalArgumentException();
      }
      this.l = l;
      this.r = r;
    }
    public int eval() {
      return l.eval() / r.eval();
    }
    public String toString() {
      return l.toString() + " " + r.toString() + " /";
    }
  }
}