解释器模式

类图

代码

Expression

1
2
3
interface Expression{
boolean interpret(Context ctx);
}

Context

1
2
3
4
5
6
7
8
9
10
11
12
class Context{

private Map<Variable, Boolean> map = new HashMap<>();

public void assgin(Variable var, boolean value){
map.put(var, value);
}

public Boolean lookup(Variable var){
return map.get(var);
}
}

TerminalExpression

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Variable implements Expression{

@Override
public boolean interpret(Context ctx) {
return ctx.lookup(this);
}

}

class Constant implements Expression{

private Boolean value;

public Constant(Boolean value) {
this.value = value;
}

@Override
public boolean interpret(Context ctx) {
return value;
}
}

NotTerminalExpression

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class And implements Expression{

private Expression left, right;

public And(Expression left, Expression right) {
this.left = left;
this.right = right;
}

@Override
public boolean interpret(Context ctx) {
return left.interpret(ctx) && right.interpret(ctx);
}
}

class Or implements Expression{

private Expression left, right;

public Or(Expression left, Expression right) {
this.left = left;
this.right = right;
}

@Override
public boolean interpret(Context ctx) {
return left.interpret(ctx) || right.interpret(ctx);
}
}

Client

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Main {
public static void main(String args[]){

Context ctx = new Context();

Variable a = new Variable();
Constant b = new Constant(true);
ctx.assgin(a, false);

Expression result = new And(new Or(a, b), a);

System.out.println(result.interpret(ctx));
}
}

总结

优点

新文法的实现较为便捷

缺点

执行效率较低,可利用的场景比较少

复杂文法比较难维护