解释器模式
解释器模式(Interpreter Pattern)提供了评估语言的语法或表达式的方式,它属于行为型模式。这种模式实现了一个表达式接口,该接口解释一个特定的上下文。这种模式被用在 SQL 解析、符号处理引擎等。
示例演示:
创建一个生物接口,并提供一个判断的方法
1
2
3
4
5
6
7
8package test.interpreter;
/**
* 所有生物的标识
*/
public interface Organism {
public boolean isOrganism(String context);
}创建一个people实体类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17package test.interpreter;
public class People implements Organism {
private String data;
public People(String data) {
this.data = data;
}
public boolean isOrganism(String context) {
if (context.contains(data)) {
return true;
}
return false;
}
}分别编写两个判断是否是people的实体,一个是或,一个是且
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16package test.interpreter;
public class OrPeople implements Organism {
private Organism org1 = null;
private Organism org2 = null;
public OrPeople(Organism org1, Organism org2) {
this.org1 = org1;
this.org2 = org2;
}
public boolean isOrganism(String context) {
return org1.isOrganism(context) || org2.isOrganism(context);
}
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16package test.interpreter;
public class AndPeople implements Organism {
private Organism org1 = null;
private Organism org2 = null;
public AndPeople(Organism org1, Organism org2) {
this.org1 = org1;
this.org2 = org2;
}
public boolean isOrganism(String context) {
return org1.isOrganism(context) && org2.isOrganism(context);
}
}完成上述步骤,我们就可以开始演示了
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22package test.interpreter;
public class InterpreterDemo {
public static Organism getOrPeople(){
Organism o1 = new People("people");
Organism o2 = new People("animal");
return new OrPeople(o1,o2);
}
public static Organism getAndPeople(){
Organism o1 = new People("people");
Organism o2 = new People("animal");
return new AndPeople(o1,o2);
}
public static void main(String[] args) {
Organism orPeople = getOrPeople();
Organism andPeople = getAndPeople();
System.out.println("people or animal is people? "+orPeople.isOrganism("people"));
System.out.println("people and animal is people? "+andPeople.isOrganism("people"));
}
}演示结果:
1
2people or animal is people? true
people and animal is people? false
说明:
优点: 1、可扩展性比较好,灵活。 2、增加了新的解释表达式的方式。 3、易于实现简单文法。
缺点: 1、可利用场景比较少。 2、对于复杂的文法比较难维护。 3、解释器模式会引起类膨胀。 4、解释器模式采用递归调用方法。