1. 概念
给定一个语言,定义它的文法的一种表示,并定义一个解释器,
这个解释器使用该表示来解释语言中的句子。
2. 创建表达式抽象类
public abstract class Expression {
public void interpret(PlayContext context){
if(context.getText().length() == 0){
return;
}else{
String playKey = context.getText().substring(0,1);
context.setText(context.getText().substring(2));
double playValue = Double.valueOf(context.getText().substring(0,context.getText().indexOf(" ")));
context.setText(context.getText().substring(context.getText().indexOf(" ") +1));
excute(playKey,playValue);
}
}
public abstract void excute(String key,double value);
}
3. 创建具体表达式类
1.
/**
* @author zlc
* @created 2017/12/24
*/
public class Scale extends Expression{
@Override
public void excute(String key, double value) {
String scale = "";
switch ((int) value){
case 1:
scale = "低音";
break;
case 2:
scale = "中音";
break;
case 3:
scale = "高音";
break;
}
System.out.print(scale +" ");
}
}
2.
/**
* @author zlc
* @created 2017/12/24
*/
public class Note extends Expression{
@Override
public void excute(String key, double value) {
String note = "";
switch (key){
case "C":
note = "1";
break;
case "D":
note = "2";
break;
case "E":
note = "3";
break;
case "F":
note = "4";
break;
case "G":
note = "5";
break;
case "A":
note = "6";
break;
case "B":
note = "7";
break;
}
System.out.print(note+" ");
}
}
4. 创建Context类
public class PlayContext {
private String text;
public void setText(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
5. 测试类
@org.junit.Test
public void test(){
PlayContext context = new PlayContext();
System.out.println("上海滩:");
String text = "O 2 E 0.5 G 0.5 A 3 E 0.5 G 0.5 D 3 E 0.5 G 0.5 A 0.5 O 3 C 1 O 2 A 0.5 G 1 C 0.5 E 0.5 E 0.5 D 3 ";
context.setText(text);
try {
while (context.getText().length() > 0) {
Expression expression = null;
String str = context.getText().substring(0, 1);
switch (str) {
case "O":
expression = new Scale();
break;
case "C":
case "D":
case "E":
case "F":
case "G":
case "A":
case "B":
expression = new Note();
break;
}
expression.interpret(context);
}
}catch (Exception e){
System.out.println(e.getMessage());
}
}
5.小结
当一个语言需要解释执行,并且你可将该语言中的句子表示为一个抽象语法树时,可使用解释器模式。容易改变和扩展文法。