express ::= value | plus | minus
plus ::= express + express
minus ::= express - express
value ::= integer
public class Test {
public static void main(String[] args) {
Environment environment = new Environment();
ParameterExpress a = new ParameterExpress("A");
ParameterExpress b = new ParameterExpress("B");
ParameterExpress c = new ParameterExpress("C");
ParameterExpress d = new ParameterExpress("D");
environment.add(a, 11);
environment.add(b, 2);
environment.add(c, 4);
environment.add(d, 6);
AbstractExpress express = new PlusExpress(new SubtractionExpress(new PlusExpress(a, b), c), d);
Integer interpret = express.interpret(environment);
System.out.println(express);
System.out.println(interpret);
}
}
// 抽象表达式
abstract class AbstractExpress {
abstract Integer interpret(Environment environment);
}
// 环境角色,理解成容器,存储具体参数角色
class Environment {
// 参数节点
private Map<ParameterExpress, Integer> parameterExpressIntegerMap = new HashMap<>();
// 存入数据
public void add(ParameterExpress parameterExpress, Integer value) {
parameterExpressIntegerMap.put(parameterExpress, value);
}
// 获取数据
public Integer get(ParameterExpress parameterExpress) {
return parameterExpressIntegerMap.get(parameterExpress);
}
}
// 具体变量角色
class ParameterExpress extends AbstractExpress {
// 变量名称
private String name;
ParameterExpress(String name){ this.name = name;}
@Override
Integer interpret(Environment environment) {
// 获取变量数据
return environment.get(this);
}
@Override
public String toString() {
return name;
}
}
// 具体加法表达式
class PlusExpress extends AbstractExpress {
// 左边表达式
private AbstractExpress left;
// 右边表达式
private AbstractExpress right;
PlusExpress(AbstractExpress left, AbstractExpress right) {
this.left = left;
this.right = right;
}
@Override
Integer interpret(Environment environment) {
// 加法表达式规则
return left.interpret(environment) + right.interpret(environment);
}
@Override
public String toString() {
return left + "+" + right;
}
}
// 具体减法表达式
class SubtractionExpress extends AbstractExpress {
// 左边表达式
private AbstractExpress left;
// 右边表达式
private AbstractExpress right;
SubtractionExpress(AbstractExpress left, AbstractExpress right) {
this.left = left;
this.right = right;
}
@Override
Integer interpret(Environment environment) {
// 减法表达式规则
return left.interpret(environment) - right.interpret(environment);
}
@Override
public String toString() {
return left + "-" + right;
}
}