【注意】最后更新于 January 22, 2018,文中内容可能已过时,请谨慎使用。
本文来说下java设计模式之解释器模式。
这个模式我是看的一头雾水,根据原文
>Given a language, define a represention for its grammar along with aninterpreter
that uses the representation to interpret sentences in thelanguage
很蒙,这个我在网上看到的解释是就是如果一个特定类型的问题发生的频率足够高的话,就可以把该问题的各个实例表述为一个简单语言中的句子。这样通过构建一个解释器来解决该问题。
然后我在网上看到的大部分都说在日常开发中应用比较少,我也不懂,想着跳过去的,不过看到要写完设计模式,就勉为其难写上吧。
解释器主要有这几个结构
1. 抽象表达式:抽象的解释操作,一个接口
2. 终结符就是具体的表达式,一些数据内容
3. 非终结表达式是一些数据操作
4. 上下文角色:包含一些全局的信息,数据内容等。
5. 客户端:就是构建语句以及进行解释了
废话不多说了,来看代码吧。
1
2
3
|
public interface Expression {
int interpret(Context ctx);
}
|
然后我们看下实现的变量
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public class Constant implements Expression {
private int v;
public Constant(int v) {
this.v = v;
}
@Override
public int interpret(Context ctx) {
return v;
}
}
|
还有些其他的操作
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
30
31
32
33
34
35
36
37
|
public class Variable implements Expression{
@Override
public int interpret(Context ctx) {
return ctx.getValue(this);
}
}
public class Add implements Expression {
private Expression left,right;
public Add(Expression left, Expression right) {
this.left = left;
this.right = right;
}
@Override
public int interpret(Context ctx) {
return left.interpret(ctx)+right.interpret(ctx);
}
}
public class Subtract implements Expression {
private Expression left, right;
public Subtract(Expression left, Expression right) {
this.left = left;
this.right = right;
}
@Override
public int interpret(Context ctx) {
return left.interpret(ctx) - right.interpret(ctx);
}
}
|
当然,还有上下文变量
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public class Context {
private Map<Variable,Integer> var=new HashMap<>();
public void addValue(Variable a,int b){
var.put(a,b);
}
public int getValue(Variable a){
return var.get(a);
}
}
|
最后我们来看下客户端的操作了
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
public class Client {
public static void main(String[] args) {
Variable a=new Variable();
Variable b=new Variable();
Context ctx=new Context();
ctx.addValue(a,4);
ctx.addValue(b,5);
Constant con=new Constant(7);
Expression e=new Subtract(new Add(a,b),con);
System.out.println(e.interpret(ctx));
}
}
|
恩,就这样吧。
.............分割线....................
这一篇很是敷衍(实际其他的也很敷衍),主要是我也不懂,完全没见过。没有具体的应用场景的话也不好明白。
如果以后用到的话,我会再来尝试修改本文的。