解释器模式:
给定一中语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子。
// 表达式类
public abstract class Expression {
public void interpret(PlayContext context) {
if (context.getContext().length() == 0) {
return;
} else {
String playKey = context.getContext().substring(0, 1);
context.setContext(context.getContext().substring(2));
double playValue = Double.parseDouble(context.getContext().substring(0, context.getContext().indexOf(" ")));
context.setContext(context.getContext().substring(context.getContext().indexOf(" ") + 1));
excute(playKey, playValue);
}
}
public abstract void excute(String key, double value);
}
// 音符类
public class Note extends Expression {
@Override
public void excute(String key, double value) {
String note = null;
if (key.equals("C"))
note = "1";
if (key.equals("D"))
note = "2";
if (key.equals("E"))
note = "3";
if (key.equals("F"))
note = "4";
if (key.equals("G"))
note = "5";
if (key.equals("A"))
note = "6";
if (key.equals("B"))
note = "7";
System.out.print(" " + note + " ");
}
}
// 音阶类
public class Scale extends Expression {
@Override
public void excute(String key, double value) {
String scale = null;
int intKey = (int) value;
if (intKey == 1)
scale = "low scale";
if (intKey == 2)
scale = "mid scale";
if (intKey == 3)
scale = "high scale";
System.out.print(" " + scale + " ");
}
}
// 演奏内容类
public class PlayContext {
private String context;
public String getContext() {
return context;
}
public void setContext(String context) {
this.context = context;
}
}
// 客户端
public class InterpreterMain {
public static void main(String[] args) {
PlayContext context = new PlayContext();
String content = "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 D 3 ";
context.setContext(content);
Expression exp = null;
try {
while (context.getContext().length() > 0) {
String str = context.getContext().substring(0, 1);
if (str.equals("O")) {
exp = new Scale();
} else {
exp = new Note();
}
exp.interpret(context);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
用解释器模式就如同你开发了一个编程语言或脚本给自己或别人用。用了解释器模式就意味着很容易改变和拓展文法,因为该模式使用类来表示文法规则,你可以使用继承来改变和拓展该文法。