package composite;
public class Expression implements Element{
private Element e1,e2;
private char op;
public Expression(Element e1,Element e2,char op){
this.e1=e1;
this.e2=e2;
this.op=op;
}
public double getValue(){
switch(op){
case '+' :return e1.getValue()+e2.getValue();
case '-' :return e1.getValue()-e2.getValue();
case '*' :return e1.getValue()*e2.getValue();
case '/' :return e1.getValue()/e2.getValue();
default: throw new RuntimeException("无效的运算符!");
}
}
public static void main(String[] args) {
Number n1 = new Number(1);
Number n2 = new Number(2);
Expression e1 = new Expression(n1, n2, '*');
System.out.println(e1.getValue());
}
}
package composite;public class Number implements Element{private double num;public Number(double num){this.num=num;}public double getValue(){return num;}}
package composite;interface Element { double getValue();}