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